使用日历来确定AM或PMdate

使用日历来确定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){} 

我想根据当前时间将时间设置为AM或PM。 也出于某种原因Calendar.MONTH值不给我正确的月份。 这是为什么我不得不加1。只是想知道这是否正常?

 int months = 1 + c.get(Calendar.MONTH); 

Solutions Collecting From Web of "使用日历来确定AM或PMdate"

这是正常的。 因为Calendar.MONTH的索引从0开始。所以为什么你需要+1才能得到正确的月份。

确定AM与PM是基于小时的直接计算。 代码如下:

 String timeString=""; int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); if (hour == 0) { timeString = "12AM (Midnight)"; } else if (hour < 12) { timeString = hour +"AM"; } else if (hour == 12) { timeString = "12PM (Noon)"; } else { timeString = hour-12 +"PM"; } 

只需检查calendar.get(Calendar.AM_PM) == Calendar.AM

 Calendar now = Calendar.getInstance(); if(now.get(Calendar.AM_PM) == Calendar.AM){ // AM }else{ // PM } 

我试过这个 ,但是没有用。 我必须获得AM_PM值,然后进行比较:

 int AM_PM = c.get(Calendar.AM_PM); if(AM_PM == Calendar.AM){ ... ... 

这是解决办法:

  Calendar c = Calendar.getInstance(); int AM_PM = c.get(Calendar.AM_PM); if(AM_PM == Calendar.AM){ //AM }else{ //PM }