How to change the date format from YYMMDD to YYYY-

2019-03-07 07:10发布

问题:

I am getting the date format from the machine readable code as YYMMDD, how can i change it into YYYY-MM-DD ? for example am getting 871223(YYMMDD) i wand to change it into 1987-12-23(YYYY-MM-DD) is it possible ? can anyone help me with some sample codes?

回答1:

The code goes something like this:

SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");

try {

String reformattedStr = myFormat.format(fromUser.parse(inputString));
} catch (ParseException e) {
e.printStackTrace();
}


回答2:

Simple steps to follow and achieve what you want:

for example date is:

  String date = "871223";

Create SimpleDateFormat with source pattern

    SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");

get the date object by parsing the date

    Date d1 = sdf.parse(date);

Change the pattern to the target one

    sdf.applyPattern("yyyy-MM-dd");

Format as per the target pattern

    System.out.println(sdf.format(d1));

Hope this helps.