gpt4 book ai didi

java - 将 String 转换为 (yyyy-MM-dd) 格式的 java.util.Date,返回类型为 Date

转载 作者:行者123 更新时间:2023-12-02 03:57:19 26 4
gpt4 key购买 nike

我正在尝试通过这种方式将 String 转换为 java.util.date,

我的输入字符串是:“2013-09-18”

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateAndTime {

public static void main(String[] args) throws Exception {

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date convertedCurrentDate = sdf.parse("2013-09-18");
String strDate = new SimpleDateFormat("yyyy-MM-dd").format(convertedCurrentDate);
System.out.println(strDate);

}
}

此处,convertedCurrentDate 的输出为““Wed Sep 18 00:00:00 IST 2013”​​”。

实际上我想以这种方式获得输出,2013-09-18,而不是“”Wed Sep 18 00:00:00 IST 2013”​​

所以,我尝试了这个方法,

String strDate = new SimpleDateFormat("yyyy-MM-dd").format(convertedCurrentDate);
System.out.println(strDate);

这给我的输出为 2013-09-18。

但问题是我得到了这个“2013-09-18”作为字符串。

我想要的是 2013-09-18 与 java.util.date 数据类型而不是字符串

即,

need to cast strDate to java.util.date.

有人可以帮我解决这个问题吗?

谢谢

最佳答案

原因:
使用 println 时,java 显式调用该对象上的 toString 方法。在 Date 对象上调用 toString 时,它可能使用其默认日期格式,从而导致上述输出。

解决方案:仅出于打印目的,做你正在做的事情

String strDate = new SimpleDateFormat("yyyy-MM-dd").format(convertedCurrentDate);  
System.out.println(strDate);

关于java - 将 String 转换为 (yyyy-MM-dd) 格式的 java.util.Date,返回类型为 Date,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35314618/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com