Java 将字符串转换为 am/pm 格式的日期和时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23751172/
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
convert string to date and time as am/pm format
提问by Developer
string : 2014-04-25 17:03:13
using SimpleDateFormat is enough to format? or otherwise i will shift to any new API?
使用 SimpleDateFormat 足以格式化吗?否则我会转向任何新的 API?
Date date = new Date(string);
DateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd");
out.println( dateFormat.format (date));
My expected result is (India zone):
我的预期结果是(印度区):
Date : 25-04-2014
Time : 05:03 PM
采纳答案by Bohemian
Remembering that Date
objects have no inherent format, you need two DateFormat
objects to produce the result you seek - one to parse and another to format:
记住Date
对象没有固有格式,您需要两个DateFormat
对象来生成您寻求的结果 - 一个用于解析,另一个用于格式化:
String input = "2014-04-25 17:03:13";
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateFormat outputFormat = new SimpleDateFormat("'Date : 'dd-MM-yyyy\n'Time : 'KK:mm a");
System.out.println(outputFormat.format(inputFormat.parse(input)));
Output:
输出:
Date : 25-04-2014
Time : 05:03 PM
Note the use of quoted sequences in the format, such a "'Date : '"
, which is treated as a literal within the format pattern.
请注意格式中引用序列的使用,例如 a "'Date : '"
,它被视为格式模式中的文字。
回答by hashplus
回答by Anil Satija
Try given below sample code:
尝试给出以下示例代码:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
//Output: 2013-05-20 10:16:44
For more functionalities on Data and Time try Joda-Time API.
有关数据和时间的更多功能,请尝试Joda-Time API。
回答by Pawan asati
I custom onTimeSet()
function . Send the hour
and minutes
to it. It will return the time with format am and pm
我自定义onTimeSet()
函数。发送hour
和minutes
到它。它将返回时间format am and pm
public static String onTimeSet( int hour, int minute) {
Calendar mCalen = Calendar.getInstance();;
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format_local = mCalen.get(Calendar.HOUR);
int hourOfDay_local = mCalen.get(Calendar.HOUR_OF_DAY);
int minute_local = mCalen.get(Calendar.MINUTE);
int ampm = mCalen.get(Calendar.AM_PM);
String minute1;
if(minute_local<10){
minute1="0"+minute_local;
}
else
minute1=""+minute_local;
String ampmStr = (ampm == 0) ? "AM" : "PM";
// Set the Time String in Button
if(hour12format_local==0)
hour12format_local=12;
String selecteTime=hour12format_local+":"+ minute1+" "+ampmStr;
retrun selecteTime;
}