简体   繁体   中英

How to format date/time string? (Java)

Hi can anyone help please? I am trying to format a date and time string. Currently it looks like this " 20160112T110000Z " and I need it to be " 2016-01-12T11:00:00Z "

The string without the special characters are returned from a 3rd party recurrence library. I need to convert it to have the special characters before parsing it to a Calendar object.

Can anyone help please?

The code that I have so far looks like:

 final String TIMEFORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
 String string = "20160112T110000Z";
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    Date date = format.parse(string);
    System.out.println(date); 

However this just does not work.

Any suggestions are appreciated

You have to read the string with a format matching the source, this gives you a correct Date .

Then simply write it with the format you want :

    String string = "20160112T110000Z";

    String originalStringFormat = "yyyyMMdd'T'HHmmss'Z'";
    String desiredStringFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'";

    SimpleDateFormat readingFormat = new SimpleDateFormat(originalStringFormat);
    SimpleDateFormat outputFormat = new SimpleDateFormat(desiredStringFormat);

    try {
        Date date = readingFormat.parse(string);
        System.out.println(outputFormat.format(date));
    } catch (ParseException e) {

        e.printStackTrace();
    }

try this

DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
   // you can change format of date
  Date date = formatter.parse(strDate);
  Timestamp timeStampDate = new Timestamp(date.getTime());

  return timeStampDate;

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