如何以AM/PM格式显示时间

7

我想要以AM/PM格式显示时间。 例如:9:00 AM 我还想进行加减操作。我的事件从上午9:00开始,我想添加分钟来获取结果计划。 除了制作自定义时间类,我该怎么做呢?

开始时间为9:00 AM 添加45分钟后, 开始时间为9:45 AM


可能是Java字符串转日期转换的重复问题,以及这个这个 - Basil Bourque
10个回答

16

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 至 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));

1
为什么要使用“aa”作为掩码?单个字母“a”不够吗? - Scary Wombat
1
@ScaryWombat 应该是这样的,但我双击了超过的值,所以我就有了一种节奏 ;) - MadProgrammer

3

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

大多数其他答案中使用的SimpleDateFormat、Date和Calendar类设计不佳(尤其是第一个,臭名昭著),而且已经过时。自从四年前提出这个问题以来,现代Java日期和时间API——java.time已经发布。
对于要显示给用户的时间,我通常建议使用内置格式,可以通过DateTimeFormatter.ofLocalizedDate、.ofLocalizedTime和.ofLocalizedDateTime获取。如果您在某些情况下有特定的格式化需求,而内置格式无法满足,您也可以指定自己的格式,例如:
    DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:mm a", Locale.US);

这个特定的示例是无意义的,因为它与上面的示例给出了相同的结果,但你可以用它作为起点并根据需要进行修改。

链接: Oracle教程: 日期和时间,讲解如何使用java.time


0
Calendar cl = new GregorianCalendar();
int a = cl.get(Calendar.AM_PM);
if(a == 1) {
                        lbltimePeriod.setText("PM");
                    }
                    else
                    {
                        lbltimePeriod.setText("AM");
                    }

这绝对能解决你的问题,对我百分之百有效。


问题是三年前提出的,已经有一个被接受的答案。此外,您的解决方案并没有回答这个问题。OP要求以AM/PM格式显示时间。您的解决方案只返回AM或PM。 - Hintham

0
   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();
        }
    });

0

在这里找到许多类似这个链接的例子。

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


0

使用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

0
最简单的方法是使用日期格式-h:mm a,其中
h - Hour in am/pm (1-12)
m - Minute in hour
a - Am/pm marker
Code snippet :

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

日期格式化 dateFormat = new SimpleDateFormat("hh:mm a");

0

0
使用SimpleDateFormat对象来格式化时间和Calendar对象与日期一起添加到Date对象上。

-1

有一个简单的代码可以生成带上午/下午时间,这里是我给你的代码,请检查:

import java.text.SimpleDateFormat; import java.util.Date;

public class 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));

} }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接