简体   繁体   中英

Java convert date from one format to another

How can I convert date form to

2013-01-10 09:49:19

to

10th Jan.

both values are of string types.

I added the code to work out the correct suffix as this isn't part of the standard JDK. To be fair that's probably the only bit of this question that isn't just a SimpleDateFormat#format() call.

static String[] suffixes =
          //    0     1     2     3     4     5     6     7     8     9
             { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th",
          //    10    11    12    13    14    15    16    17    18    19
               "th", "th", "th", "th", "th", "th", "th", "th", "th", "th",
          //    20    21    22    23    24    25    26    27    28    29
               "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th",
          //    30    31
               "th", "st" };

public static void main(String args[]) throws ParseException {
    String string = "2013-01-10 09:49:19";
    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH).parse(string);
    SimpleDateFormat dayFormat = new SimpleDateFormat("dd");
    SimpleDateFormat monthFormat = new SimpleDateFormat("MMM");
    String dayStr =
            dayFormat.format(date)
                    + suffixes[Integer.parseInt(dayFormat.format(date))]
                    + " " + monthFormat.format(date) + ".";
    System.out.println(dayStr);
}
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2013-01-10 09:49:19");
String format = new SimpleDateFormat("dd'th' MMM").format(date);
System.out.println(format);

Output is:

10th Jan

Use the DateFormat class

DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.ENGLISH);

System.out.println(df.parse(myDateInString));

I think you should surround the statements in try catch for possible exceptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM