我的日期格式为" 12-JAN-15 03.51.22.638000000 AM"。 我希望它转换为" 12-01-15 00:00:00.000" 即使有小时,小时和秒等,我只想输出零。
答案 0 :(得分:2)
您想要将一种日期格式转换为另一种日期格式。 This answer正是如此。它声明
DateFormat originalFormat = new SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat("yyyyMMdd");
Date date = originalFormat.parse("August 21, 2012");
String formattedDate = targetFormat.format(date); // 20120821
在您的情况下,原始格式和目标格式如下
原始格式:dd-MMM-yy hh.mm.ss.N a
目标格式:dd-MM-yy hh:mm:ss:S
我不知道如何用0替换时间数据。也许字符串操作是你的情况。但是如果你想要更多控制,那么你可以做这样的事情。
Calendar cal = Calendar.getInstance();
cal.setTime(date); // this is the date we parsed above
cal.set(Calendar.HOUR_OF_DAY,0);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
formattedDate = targetFormat.format(cal.getTime());
修改强> @ Sufiyan Ghori提供了一种更清洁的方式。
答案 1 :(得分:1)
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("MM-dd-yy:hh:mm:ss:nn"); // n = nano-of-second
LocalDateTime today = LocalDateTime.of(LocalDate.of(2015, 1, 15),
LocalTime.of(00, 00, 00, 00));
System.out.println(today.format(formatter));
<强> 输出 强>
01-15-15:12:00:00:00
<强>解释强>
LocalDateTime.of(LocalDate.of(int Year, int Month, int Day),
LocalTime.of(int Hour, int Minutes, int Seconds, int nanoOfSeconds));
答案 2 :(得分:0)
String dateInString = "12-JAN-15 10.17.07.107000000 AM";
dateInString = dateInString.substring(0, 9);
Date date = null;
try {
date = new SimpleDateFormat("dd-MMM-yy", Locale.ENGLISH).parse(dateInString);
} catch (ParseException e) {
e.printStackTrace();
}
String newFormat = new SimpleDateFormat("dd-MM-yy 00:00:00.000").format(date);
System.out.println(newFormat);
答案 3 :(得分:0)
String string = "January 2, 2010";
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = format.parse(string);
System.out.println(date); // Sat Jan 02 00:00:00 GMT 2010
您可以按照此javadoc进行操作,列出所有可用的格式模式:
G Era designator Text AD
y Year Year 1996; 96
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day in week Text Tuesday; Tue
u Day number of week Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT- 08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00
您可以参考此answer获取详细说明。