字符串到目前为止不能正常工作 [英] String to date not working properly

查看:128
本文介绍了字符串到目前为止不能正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试半小时,通过使用以下代码将字符串转换为日期:

I am trying from half an hour to convert string to date by using following code:

SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd");
Date lastCharged = dateFormat.parse(lastChargeDate); 

每次运行此代码时,系统返回的日期为 Sun Dec 29 00:00:00 PKT 2013 即使我手动更改日期是系统的响应。

Every time I run this code the date returned by the system is Sun Dec 29 00:00:00 PKT 2013 Even if i changed the date manually same is the response by the system.

在这方面有任何帮助很多工作暂停只是因为这个错误。

Any help in this regard a lot of work is suspended just because of this blunder.

推荐答案

DateFormat#parse()方法将String转换为Date 。它不会改变转换日期中的任何内容,这意味着它不存储构造它们的格式。

DateFormat#parse() method just convert the String to Date. It doesn't change anything in the converted Date it means it doesn't store the format from which it is constructed.

无论何时再次打印Date对象,都会打印在 toString()实现中,这是你正在获得的。

Whenever you print the Date object again then it prints in its default toString() implementation that's what you are getting.

你需要再次打印它格式,然后使用 DateFormat#format()方法。

It you need to print it again in specific format then use DateFormat#format() method.

格式应为 yyyy-MM -dd 而不是 YYYY-MM-dd

示例代码: p>

Sample code:

String oldDate="2014-06-07";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date=dateFormat.parse(oldDate);
System.out.println(date);

String newDate=dateFormat.format(date);
System.out.println(newDate);

输出:

Sat Jun 07 00:00:00 IST 2014
2014-06-07

这篇关于字符串到目前为止不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆