简体   繁体   English

在Android中解析yyyy-MM-DD字符串到日期yyyy-MM-DD?

[英]Parse yyyy-MM-DD String to Date yyyy-MM-DD in Android?

String startDateStr = "2017-02-03"
DateFormat formatter = new SimpleDateFormat("yyyy-MM-DD",Locale.US);
Date date = (Date)formatter.parse(startDateStr);    

2017-02-03 date is parsed to Tue Jan 03 00:00:00 GMT+05:45 2017 2017-02-03日期被解析为Tue Jan 03 00:00:00 GMT+05:45 2017

Did I miss something?我错过了什么?

Update更新

I needed a string to be converted to a date object while maintaining the same format.我需要将字符串转换为日期对象,同时保持相同的格式。

The reason for this is I want to make use of public boolean after(Date when) method这样做的原因是我想使用public boolean after(Date when)方法

This will work ^_^这将工作^_^

DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
DateFormat outputFormat = new SimpleDateFormat("dd MMM yyyy");
String startDateStr ="2017-02-03";
Date date = null;
try {
    date = inputFormat.parse(startDateStr);
    String startDateStrNewFormat = outputFormat.format(date);
} catch (ParseException e) {
    e.printStackTrace();
}

Little explanation of your output :您的输出的小解释:

D is Day in year (1-365) D是一年中的第几天 (1-365)
d is day in month (1-31) d是月中的第几天 (1-31)

Check the document检查文件

在此处输入图片说明

Yes you missed something.是的,你错过了一些东西。 You used DD instead of dd in your yyyy-MM- DD format string.您在 yyyy-MM- DD格式字符串中使用了DD而不是dd Here is how you do it:这是你如何做到的:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");  
String formattedDate = sdf.format(new Date());

Use SimpleDateFormat type for fomatter.使用 SimpleDateFormat 类型作为格式化程序。 You are creating DateFormat object but using SimpleDateFormat.您正在创建 DateFormat 对象,但使用的是 SimpleDateFormat。

String startDateStr = "2017-02-03"
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
Date date = (Date)formatter.parse(startDateStr);  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM