【问题标题】:java get date marker field(am/pm)java获取日期标记字段(上午/下午)
【发布时间】:2010-02-24 05:49:19
【问题描述】:

我需要在日期对象中获取字段 AM/PM。我怎样才能得到它?

这是我的代码。

String startTime ="01:05 PM";
 SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");

 Date st = sdf.parse(startTime);

【问题讨论】:

    标签: java


    【解决方案1】:

    您可以使用Calendar

    Calendar cal = Calendar.getInstance();
    cal.setTime(st);
    if (cal.get(Calendar.AM_PM) == Calendar.PM) {
      ...
    }
    

    确保您在执行此操作时没有时区不匹配。

    【讨论】:

    • @cletus 嗨,你会更新你的代码吗?因为现在它在 android studio 中给出了错误。
    【解决方案2】:

    日历可能是最好的,但您也可以使用 DateFormat:

    String amPm = new SimpleDateFormat("aa").format(time);
    

    时区警告也适用于此。

    【讨论】:

      【解决方案3】:

      请试试这个

      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss_aa");
          Calendar cal = Calendar.getInstance();
          Log.d("Time", ""+dateFormat.format(cal.getTime()));
          int day = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
          System.out.println("time => " + namesOfDays[day-1]+"_"+dateFormat.format(cal.getTime()));
      

      【讨论】:

        【解决方案4】:

        使用这个..

        String getTime(String milliseconds) {
        
            String time = "";
            Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(Long.parseLong(milliseconds));
        
            time = cal.get(Calendar.HOUR) + " : " + cal.get(Calendar.MINUTE);
        
            if(cal.get(Calendar.AM_PM)==0)
                time=time+" AM";
            else
                time=time+" PM";
        
            return time;
        
        }
        

        【讨论】:

          【解决方案5】:

          Calendar也可以做

          Calendar cal = Calendar.getInstance();
          cal.setTime(st);
          String meridiem = cal.getDisplayName(Calendar.AM_PM, Calendar.SHORT, Locale.getDefault())
          

          meridiem 现在根据您的代码等于“PM”。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-09-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-03-28
            相关资源
            最近更新 更多