How to get the given date string format(pattern) in java?

后端 未结 10 1680
抹茶落季
抹茶落季 2020-11-30 04:41

I want to get the format of a given date string.

Example: I have a string like 2011-09-27T07:04:21.97-05:00 and the date format of this string is

10条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 05:14

    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) {
    
                    }
                }
            }
        }
    }
    

提交回复
热议问题