【问题标题】:How can I display time in AM/PM format如何以 AM/PM 格式显示时间
【发布时间】:2014-07-31 05:01:30
【问题描述】:

我想以 AM / PM 格式显示时间。 示例:上午 9:00 我也想执行加减运算。我的活动将从上午 9:00 开始。我想增加分钟来获得结果计划事件。 除了制作自定义 Time 类之外,我该怎么做?

上午 9:00 开始 添加 45 分钟,添加后 开始时间上午 9 点 45 分

【问题讨论】:

标签: java datetime


【解决方案1】:

SimpleDateFormat 开头,这将允许您解析和格式化时间值,例如...

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
try {
    // Get the start time..
    Date start = sdf.parse("09:00 AM");
    System.out.println(sdf.format(start));
} catch (ParseException ex) {
    ex.printStackTrace();
}

有了这个,您就可以使用Calendar 来操作日期值的各个字段...

Calendar cal = Calendar.getInstance();
cal.setTime(start);
cal.add(Calendar.MINUTE, 45);
Date end = cal.getTime();

然后把它们放在一起......

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
try {
    Date start = sdf.parse("09:00 AM");
    Calendar cal = Calendar.getInstance();
    cal.setTime(start);
    cal.add(Calendar.MINUTE, 45);
    Date end = cal.getTime();

    System.out.println(sdf.format(start) + " to " + sdf.format(end));
} catch (ParseException ex) {
    ex.printStackTrace();
}

输出09:00 AM to 09:45 AM

更新

或者你可以使用JodaTime...

DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendHourOfDay(2).appendLiteral(":").appendMinuteOfHour(2).appendLiteral(" ").appendHalfdayOfDayText().toFormatter();
LocalTime start = LocalTime.parse("09:00 am", dtf);
LocalTime end = start.plusMinutes(45);

System.out.println(start.toString("hh:mm a") + " to " + end.toString("hh:mm a"));

或者,如果您使用的是 Java 8,那么新的日期/时间 API...

DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendPattern("hh:mm a").toFormatter();
LocalTime start = LocalTime.of(9, 0);
LocalTime end = start.plusMinutes(45);

System.out.println(dtf.format(start) + " to " + dtf.format(end));

【讨论】:

  • 为什么要使用 aa 的掩码? a还不够吗?
  • @ScaryWombat 应该是,但我双击了超过的值,所以我得到了一个节奏;)
【解决方案2】:

java.time

我想贡献现代答案

    // create a time of day of 09:00
    LocalTime start = LocalTime.of(9, 0);
    // add 45 minutes
    start = start.plusMinutes(45);

    // Display in 12 hour clock with AM or PM
    DateTimeFormatter timeFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)
            .withLocale(Locale.US);
    String displayTime = start.format(timeFormatter);
    System.out.println("Formatted time: " + displayTime);

输出是:

格式化时间:上午 9:45

大多数其他答案中使用的SimpleDateFormatDateCalendar 类不仅设计不佳(第一个尤其是出了名的麻烦),而且自现代Java java.time 以来它们也早已过时四年多前问这个问题时,日期和时间 API 已经出现了。

对于要显示给用户的时间,我通常推荐您从DateTimeFormatter.ofLocalizedDate.ofLocalizedTime.ofLocalizedDateTime 获得的内置格式。如果您在某些情况下有内置格式无法满足的特定格式需求,您也可以指定自己的格式,例如:

    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:mm a", Locale.US);

(这个特定的例子没有意义,因为它给出了与上面相同的结果,但您可以将其作为起点并根据您的需要进行修改。)

链接: Oracle tutorial: Date Time 解释如何使用java.time

【讨论】:

    【解决方案3】:

    找到很多这样的例子here

    import java.text.SimpleDateFormat;
    
    import java.util.Date;
    
    public class Main {
    
      public static void main(String[] args) {
        Date date = new Date();
    
        String strDateFormat = "HH:mm:ss a";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        System.out.println(sdf.format(date));
      }
    }
    //10:20:12 AM
    

    DateFormat dateFormat = new SimpleDateFormat("hh:mm a");
    

    阅读this

    【讨论】:

      【解决方案4】:

      取自http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

       "h:mm a"   gives 12:08 PM
      

      要按时执行加法,请使用日历类

      http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#add(int,%20int)

       Calendar rightNow = Calendar.getInstance();  // or use your own Date
       rightNow.add (Calendar.MINUTE, 45);
      
       DateFormat dateFormat = new SimpleDateFormat("hh:mm a");
      
       System.out.println(dateFormat.format (rightNow)); --> showing as am / pm
      

      【讨论】:

        【解决方案5】:

        使用Calendar 很容易

            Calendar calendar =Calendar.getInstance();
            SimpleDateFormat sdf=new SimpleDateFormat("hh:mm a");
            sdf.format(calendar.getTime());
            System.out.println(sdf.format(calendar.getTime()));
            // i want to add 45mins now
            calendar.add(Calendar.MINUTE,45);
            System.out.println(sdf.format(calendar.getTime()));
            // i want to substract  30mins now
            calendar.add(Calendar.MINUTE,-30);
            System.out.println(sdf.format(calendar.getTime()));
        

        输出:

           10:49 AM
           11:34 AM
           11:04 AM
        

        【讨论】:

          【解决方案6】:

          使用 Simpledatetimeformat 对象格式化时间并使用带有日期的日历对象在 Date 对象上添加时间日期

          【讨论】:

            【解决方案7】:

            使用日期模式获取它的最简单方法 - h:mm a, where

            h - Hour in am/pm (1-12)
            m - Minute in hour
            a - Am/pm marker
            Code snippet :
            

            DateFormat dateFormat = new SimpleDateFormat("hh:mm a");

            【讨论】:

              【解决方案8】:
              Calendar cl = new GregorianCalendar();
              int a = cl.get(Calendar.AM_PM);
              if(a == 1) {
                                      lbltimePeriod.setText("PM");
                                  }
                                  else
                                  {
                                      lbltimePeriod.setText("AM");
                                  }
              

              这绝对会解决你的问题,它对我有用 100%

              【讨论】:

              • 问题是在三年前提出的,并且已经得到了公认的答案。您的解决方案也不能回答问题。 OP 要求以 AM/PM 格式显示时间。您的解决方案只返回 AM 或 PM。
              【解决方案9】:
                 edit_event_time.setOnClickListener(new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
                          Calendar calendar =Calendar.getInstance();
                          SimpleDateFormat sdf=new SimpleDateFormat("hh:mm a");
                          String time = sdf.format(calendar.getTime());
                          Log.e("time","time "+sdf.format(calendar.getTime()));
                          String inputTime = time, inputHours, inputMinutes;
              
                          inputHours = inputTime.substring(0, 2);
                          inputMinutes = inputTime.substring(3, 5);
              
                          TimePickerDialog mTimePicker = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {
                              @Override
                              public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
              
                                  if (selectedHour == 0) {
                                      selectedHour += 12;
                                      timeFormat = "AM";
                                  } else if (selectedHour == 12) {
                                      timeFormat = "PM";
                                  } else if (selectedHour > 12) {
                                      selectedHour -= 12;
                                      timeFormat = "PM";
                                  } else {
                                      timeFormat = "AM";
                                  }
              
                                  String selectedTime = selectedHour + ":" + selectedMinute + " " + timeFormat;
              
                                  edit_event_time.setText(selectedTime);
              
                              }
                          }, Integer.parseInt(inputHours), Integer.parseInt(inputMinutes), false);//mention true for 24 hour's time format
                          mTimePicker.setTitle("Select Time");
                          mTimePicker.show();
                      }
                  });
              

              【讨论】:

                【解决方案10】:

                有一个简单的代码可以用 AM/PH 生成时间,这是我给你的代码,请检查一下

                导入 java.text.SimpleDateFormat; 导入 java.util.Date;

                公共类 AddAMPMToFormattedDate {

                public static void main(String[] args) {

                //create Date object
                Date date = new Date();
                
                 //formatting time to have AM/PM text using 'a' format
                 String strDateFormat = "HH:mm:ss a";
                 SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
                
                 System.out.println("Time with AM/PM field : " + sdf.format(date));
                

                } }

                【讨论】:

                  猜你喜欢
                  • 2016-09-15
                  • 2013-08-19
                  • 1970-01-01
                  • 2012-02-11
                  • 2013-09-15
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多