如何从java中的String Timestamp中提取日期和时间 [英] How to extract date and time from a String Timestamp in java
问题描述
我从服务器的MySQL获取日期和时间,如下所示: String
TIMESTAMP
/ p>
I am getting date and time as a String
TIMESTAMP
from MySQL from a server in such a format:
2014-02-15 05:18:08
我想要的是在 DD-MM-YYYY
格式中提取日期,而 HH:MM:SS AM / PM
格式。此时间戳的时区也不同,我想在印度时区(IST)。
What I want is to extract the Date in DD-MM-YYYY
format and the time in HH:MM:SS AM/PM
format. Also the timezone of this timestamp is different and I want it in Indian Timezone(IST).
记住 timestamp
是 String
数据类型。
推荐答案
使用 java.text.SimpleDateFormat
和 java.util.TimeZone
哪个时区是日期字符串在?替换下面的 UTC
时区与该时区
Which timezone the date string is in? Replace the below UTC
timezone with that timezone
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sdf.parse("2014-02-15 05:18:08");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a");
sdf2.setTimeZone(TimeZone.getTimeZone("IST"));
String dateStr = sdf2.format(date); // Output: 15-02-2014 10:48:08 AM
注意: / strong>输入字符串中的小时是(24小时/ 12小时)的格式?上述示例假定它是24小时格式,因为在输入字符串中没有AM / PM信息。
Note: In which format the hour is in (24 hour/ 12 hour) in your input string? The above example assumes that it is in 24 hour format because there in no AM/PM info in the input string.
如果输入字符串也是12小时格式,那么您的输入字符串应该提到AM / PM信息,如 2014-02-15 05:18:08 PM
。在这种情况下,将 sdf
修改为新的SimpleDateFormat(yyyy-MM-dd hh:mm:ss a)
If the input string is also in 12 hour format then your input string should mention AM/PM info also such as 2014-02-15 05:18:08 PM
. In that case, modify the sdf
to new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a")
======================
已编辑: =====================
======================== Edited: =====================
在评论中回答您的下一个问题如何提取日期和时间分别...
To answer your next question in comment "How to extract date and time separately"...
SimpleDateFormat sdfDate = new SimpleDateFormat("dd-MM-yyyy");
sdfDate.setTimeZone(java.util.TimeZone.getTimeZone("IST"));
SimpleDateFormat sdfTime = new SimpleDateFormat("hh:mm:ss a");
sdfTime.setTimeZone(java.util.TimeZone.getTimeZone("IST"));
String dateStr = sdfDate.format(date);
String timeStr = sdfTime.format(date);
这篇关于如何从java中的String Timestamp中提取日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!