我有一个变量 myDateString
,它包含一个日期字符串,如下所示:
2008-06-20 15:30:11.656
我正在尝试弄清楚如何将其从当前格式转换为以下格式:
June 20, 2008
我正在尝试使用 SimpleDateFormat 来实现这一点,但我似乎不太明白。到目前为止我已经
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date myDate = sdf.parse(myDateString);
System.out.println(????);
我最初的想法是使用 Date 方法,例如 getDay()、getMonth() 等,并将所有这些方法连接在一起成为我想要的字符串。不幸的是,据我所知,没有打印月份名称的方法,只能打印月份编号。
如何在 Java 中将我的日期字符串转换为所需的日期输出?
如果您使用 Date 对象(注意@RealSkeptic 的评论),您需要这样做。
public static void main(String[] args) throws ParseException {
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date d = f.parse("2008-06-20 15:30:11.656"); // Format String to a dateobject with the format provided by the String.
SimpleDateFormat f2 = new SimpleDateFormat("MMMM dd, yyyy"); // MMMM for full month name
System.out.println(f2.format(d)); // Use the second format to create the desired format as String with d as input.
}