使用日历确定上午或下午日期
使用日历类确定 AM 或 PM 时间。
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
int minutes = c.get(Calendar.MINUTE);
int hours = c.get(Calendar.HOUR);
int years = c.get(Calendar.YEAR);
int months = 1 + c.get(Calendar.MONTH);
int days = c.get(Calendar.DAY_OF_MONTH);
int AM_orPM = c.get(Calendar.AM_PM);
try{
if (hours < 12)
{
String PM = "";
if (AM_orPM == 1)
{
PM = "PM";
}
timestamp.setText("Refreshed on " + months + "-"
+ days + "-" + years + " " + hours + ":" + minutes + ":" + seconds + " " + PM);
timestamp.setTextSize(17f);
timestamp.setTextColor(Color.GREEN);
}
else if (hours > 12)
{
String AM = "";
if (AM_orPM == 0)
{
AM = "AM";
}
hours = hours - 12;
timestamp.setText("Refreshed on " + years + "-"
+ months + "-" + days + " " + hours + ":" + minutes + ":" + seconds + AM);
timestamp.setTextSize(17f);
timestamp.setTextColor(Color.GREEN);
}
}
catch (Exception e){}
我想根据当前时间将时间设置为上午或下午。 另外由于某种原因,Calendar.MONTH 值没有给我正确的月份。差了 1,所以我必须加 1。只是想知道这是否正常?
int months = 1 + c.get(Calendar.MONTH);
Using the calendar class to determine AM or PM times.
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
int minutes = c.get(Calendar.MINUTE);
int hours = c.get(Calendar.HOUR);
int years = c.get(Calendar.YEAR);
int months = 1 + c.get(Calendar.MONTH);
int days = c.get(Calendar.DAY_OF_MONTH);
int AM_orPM = c.get(Calendar.AM_PM);
try{
if (hours < 12)
{
String PM = "";
if (AM_orPM == 1)
{
PM = "PM";
}
timestamp.setText("Refreshed on " + months + "-"
+ days + "-" + years + " " + hours + ":" + minutes + ":" + seconds + " " + PM);
timestamp.setTextSize(17f);
timestamp.setTextColor(Color.GREEN);
}
else if (hours > 12)
{
String AM = "";
if (AM_orPM == 0)
{
AM = "AM";
}
hours = hours - 12;
timestamp.setText("Refreshed on " + years + "-"
+ months + "-" + days + " " + hours + ":" + minutes + ":" + seconds + AM);
timestamp.setTextSize(17f);
timestamp.setTextColor(Color.GREEN);
}
}
catch (Exception e){}
I want to set the time to AM or PM depending on the current time.
also for some reason the Calendar.MONTH value doesn't give me the correct month. It's off by one so thats why I had to add 1. Just wondering if thats normal?
int months = 1 + c.get(Calendar.MONTH);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是正常的。因为
Calendar.MONTH
的索引从 0 开始。所以这就是为什么你需要+1
才能获得正确的月份。It is normal. Because the index of the
Calendar.MONTH
starts from 0. So that why you need+1
to get the correct Month.只需检查
calendar.get(Calendar.AM_PM) == Calendar.AM
Simply check
calendar.get(Calendar.AM_PM) == Calendar.AM
确定上午与下午是基于小时的简单计算。这是代码:
Determining AM vs. PM is a straightforward calculation based on hour. Here's the code:
我尝试了这个,但它不起作用。我必须获得 AM_PM 值,然后进行比较:
这是解决方案:
I tried this, but it doesn´t work. I have to obtain the AM_PM value and then make the comparison:
It was solution: