java 如何以 AM/PM 格式显示时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25051149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I display time in AM/PM format
提问by Jeet
I wanted to display time in AM / PM format. Example : 9:00 AM I wanted to perform addition subtraction operation as well. My event will start from 9:00 AM all time. I wanted to add minutes to get the result schedule event. How can I do that other then making a custom Time class?
我想以 AM / PM 格式显示时间。示例:上午 9:00 我也想执行加减运算。我的活动将一直从上午 9:00 开始。我想添加分钟以获得结果计划事件。除了制作自定义时间类之外,我还能怎么做?
Start 9:00 AM Add 45 min, after addition Start Time 9:45 AM
开始 9:00 AM 添加 45 分钟,添加后开始时间 9:45 AM
回答by MadProgrammer
Start with a SimpleDateFormat
, this will allow you parse and format time values, for example...
以 a 开头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();
}
With this, you can then use Calendar
with which you can manipulate the individual fields of a date value...
有了这个,您就可以使用Calendar
它来操作日期值的各个字段...
Calendar cal = Calendar.getInstance();
cal.setTime(start);
cal.add(Calendar.MINUTE, 45);
Date end = cal.getTime();
And putting it all together...
并将它们放在一起......
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();
}
Outputs 09:00 AM to 09:45 AM
输出 09:00 AM to 09:45 AM
Updated
更新
Or you could use JodaTime
...
或者你可以用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"));
Or, if you're using Java 8's, the new Date/Time API...
或者,如果您使用的是 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));
回答by Ole V.V.
java.time
时间
I should like to contribute the modern answer
我想贡献现代答案
// 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);
The output is:
输出是:
Formatted time: 9:45 AM
格式化时间:上午 9:45
The SimpleDateFormat
, Date
and Calendar
classes used in most of the other answers are not only poorly designed (the first in particular notoriously troublesome), they are also long outdated since java.time, the modern Java date and time API, was already out when this question was asked more than four years ago.
大多数其他答案中使用的SimpleDateFormat
,Date
和Calendar
类不仅设计不佳(第一个特别臭名昭著),而且它们也早已过时,因为现代 Java 日期和时间 API java.time 在这个问题出现时已经过时了四年前问过。
For a time to be displayed to a user I generally recommend the built-in formats that you get from DateTimeFormatter.ofLocalizedDate
, .ofLocalizedTime
and .ofLocalizedDateTime
. Should you in some situation have particular formatting needs that are not met with the built-in formats, you may also specify your own, for example:
对于向用户显示的时间,我通常推荐您从DateTimeFormatter.ofLocalizedDate
、.ofLocalizedTime
和获得的内置格式.ofLocalizedDateTime
。如果您在某些情况下有内置格式无法满足的特定格式需求,您也可以指定自己的格式,例如:
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("h:mm a", Locale.US);
(This particular example is pointless since it gives the same result as above, but you may use it as a starting point and modify it to your needs.)
(此特定示例毫无意义,因为它给出了与上述相同的结果,但您可以将其用作起点并根据需要对其进行修改。)
Link:Oracle tutorial: Date Timeexplaining how to use java.time
.
链接:Oracle 教程:解释如何使用java.time
.
回答by Scary Wombat
as taken from http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
取自http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
"h:mm a" gives 12:08 PM
to perform addition on time use The Calendar class
要按时执行加法,请使用 Calendar 类
http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#add(int,%20int)
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
回答by Deepanshu J bedi
Find many examples like this 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");
Read this
读这个
回答by Ruchira Gayan Ranaweera
That is very easy with Calendar
这很容易 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()));
Out put:
输出:
10:49 AM
11:34 AM
11:04 AM
回答by Ruchira Gayan Ranaweera
use the Simpledatetimeformat object to format time and calander object with date to add time date on the Date obeject
使用 Simpledatetimeformat 对象格式化时间并使用日期日历对象在 Date 对象上添加时间日期
回答by Praveen Srinivasan
Easiest way to get it by using date pattern - h:mm a, where
使用日期模式获取它的最简单方法 - 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 dateFormat = new SimpleDateFormat("hh:mm a");
回答by JM Pascual
Calendar cl = new GregorianCalendar();
int a = cl.get(Calendar.AM_PM);
if(a == 1) {
lbltimePeriod.setText("PM");
}
else
{
lbltimePeriod.setText("AM");
}
This would Definitely Solve your Problem, It Works for me 100%
这绝对可以解决您的问题,它对我 100% 有效
回答by Kishore Reddy
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();
}
});
回答by Gaurav
There is a simple code to generate a time with AM/PH here is a code i give you please check this
有一个简单的代码可以用 AM/PH 生成时间,这是我给你的代码,请检查这个
import java.text.SimpleDateFormat; import java.util.Date;
导入 java.text.SimpleDateFormat; 导入 java.util.Date;
public class AddAMPMToFormattedDate {
公共类 AddAMPMToFormattedDate {
public static void main(String[] args) {
公共静态无效主(字符串 [] 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));
} }
} }