简体   繁体   中英

Convert String “1/1/1970” to a date object formatted as “19700101000000”?

I am writing Junit tests to verify data entered after it has been transformed into a different format. How would I convert a String like "1/1/1970" into a date object formatted like 19700101000000? I tried this:

DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
Date date = format.parse("1/1/1970");

But "1/1/1970" throws an Unparseable date ParseException. Thanks!

You must use different DateFormat s to parse and to format. Right now you're taking "1/1/1970" and trying to read it with the date format "yyyyMMddHHmmss". You'll need to parse with the format MM/dd/yyyy , get out a Date , and then format it with your format "yyyyMMddHHmmss".

You need to parse using one formatter, then reformat using another. Here's code for old style, and for new java.time API built into Java 8 and later.

String input = "1/1/1970";

// Using SimpleDateFormat
Date date = new SimpleDateFormat("M/d/yyyy").parse(input);
System.out.println(new SimpleDateFormat("yyyyMMddHHmmss").format(date));

// Using Java 8 java.time
LocalDate localDate = LocalDate.parse(input, DateTimeFormatter.ofPattern("M/d/uuuu"));
System.out.println(localDate.atStartOfDay().format(DateTimeFormatter.ofPattern("uuuuMMddHHmmss")));

As Louis Wasserman indicated, format.parse the input date String to a Date object. Then use that Date object as input to another SimpleDateFormat object.

Something like this :

public class DateFormatTest {

public static void main(String[] args) {
    String inputDate = args[0];
    java.util.Date d = null;
    java.text.DateFormat inputDateFormat = new java.text.SimpleDateFormat("MM/dd/yyyy");
    java.text.DateFormat outputDateFormat = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
    try {
        d = inputDateFormat.parse(intputDate);
    } catch (java.text.ParseException ex) {
        System.err.println("something horrible went wrong!");
    }
    String output = outputDateFormat.format(d);
    System.out.println("The input date of: " + inputDate + " was re-formatted to: " + output);
  }
}

Providing "1/1/1970" as the input parameter, the output is:

The input date of: 1/1/1970 was re-formatted to: 19700101000000

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