如何在java中将日期格式从YYMMDD更改为YYYY-MM-DD?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24505972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:39:13  来源:igfitidea点击:

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

javadate-format

提问by Abhi

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?

我从机器可读代码中获取日期格式为 YYMMDD,如何将其更改为 YYYY-MM-DD ?例如我得到 871223(YYMMDD) 我想把它改成 1987-12-23(YYYY-MM-DD) 有可能吗?谁能帮我一些示例代码?

采纳答案by Wilson

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();
}

回答by Sanjeev

Simple steps to follow and achieve what you want:

遵循并实现您想要的简单步骤:

for example date is:

例如日期是:

  String date = "871223";

Create SimpleDateFormatwith source pattern

使用源模式创建SimpleDateFormat

    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.

希望这可以帮助。