問題描述
我想獲取給定日期字符串的格式.
I want to get the format of a given date string.
示例:我有一個類似 2011-09-27T07:04:21.97-05:00
的字符串,該字符串的日期格式是 yyyy-MM-dd'T'HH:mm:ss.SSS
.
Example: I have a string like 2011-09-27T07:04:21.97-05:00
and the date format of this string is yyyy-MM-dd'T'HH:mm:ss.SSS
.
在這里,我想在將字符串(2011-09-27T07:04:21.97-05:00
)傳遞給將返回格式(yyyy-MM-dd'T'HH:mm:ss.SSS
),然后我將根據我的要求格式化給定的日期字符串(like yy-mm--dd or mm/dd/yyyy
).
Here I want to find out this date format when I pass string(2011-09-27T07:04:21.97-05:00
) to a method which will return the format(yyyy-MM-dd'T'HH:mm:ss.SSS
), then later I will format my given date string according to my requirement(like yy-mm--dd or mm/dd/yyyy
).
誰能告訴我如何才能實現它?
Can any one tell me how can I get it achieved?
推薦答案
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NewClass {
private static final String[] formats = {
"yyyy-MM-dd'T'HH:mm:ss'Z'", "yyyy-MM-dd'T'HH:mm:ssZ",
"yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
"yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd HH:mm:ss",
"MM/dd/yyyy HH:mm:ss", "MM/dd/yyyy'T'HH:mm:ss.SSS'Z'",
"MM/dd/yyyy'T'HH:mm:ss.SSSZ", "MM/dd/yyyy'T'HH:mm:ss.SSS",
"MM/dd/yyyy'T'HH:mm:ssZ", "MM/dd/yyyy'T'HH:mm:ss",
"yyyy:MM:dd HH:mm:ss", "yyyyMMdd", };
/*
* @param args
*/
public static void main(String[] args) {
String yyyyMMdd = "20110917";
parse(yyyyMMdd);
}
public static void parse(String d) {
if (d != null) {
for (String parse : formats) {
SimpleDateFormat sdf = new SimpleDateFormat(parse);
try {
sdf.parse(d);
System.out.println("Printing the value of " + parse);
} catch (ParseException e) {
}
}
}
}
}
這篇關于如何在java中獲取給定的日期字符串格式(模式)?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!