How to change the date format from YYMMDD to YYYY-MM-DD in java? [closed]

我与影子孤独终老i 提交于 2019-12-02 23:51:41

问题


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.



来源:https://stackoverflow.com/questions/24505972/how-to-change-the-date-format-from-yymmdd-to-yyyy-mm-dd-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!