字符串 (dd-MM-yyyy HH:mm) 转换为日期 (yyyy-MM-dd HH:mm) | Java

7

我有一个字符串,格式为"dd-MM-yyyy HH:mm",需要将其转换为格式为"yyyy-MM-dd HH:mm"的日期对象。

以下是我用来进行转换的代码:

oldScheduledDate = "16-05-2011 02:00:00";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date oldDate = (Date)formatter.parse(oldScheduledDate);

现在当我打印出oldDate时,我得到的是Sat Nov 01 02:00:00 GMT 21,完全不正确,我在这里做错了什么?
4个回答

23
    String dateSample = "10-01-2010 21:10:05";

    String oldFormat = "dd-MM-yyyy HH:mm:ss";
    String newFormat = "yyyy-MM-dd HH:mm:ss";

    SimpleDateFormat sdf1 = new SimpleDateFormat(oldFormat);
    SimpleDateFormat sdf2 = new SimpleDateFormat(newFormat);


    try {
        System.out.println(sdf2.format(sdf1.parse(dateSample)));

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

我认为你需要在你的格式末尾添加:ss,但还没有进行测试以确认。 - Mikezx6r
返回类型是String,而我们需要的是Date。怎么做? - viper
日期相同,但格式不同。旧格式 = 新格式。 - jrey

5
"yyyy-MM-dd"与"16-05-2011"看起来完全不同。嗯,为什么呢?
提示:
1.日期格式非常字面。它采用指定的格式并使用它——没有花哨的东西。
2.处理过程:输入日期字符串->转换(使用输入格式)->日期->转换(使用输出格式)->输出日期字符串
3.帖子中的代码包含一个输出格式,但没有导入格式。

我不知道,另一个选择是将字符串拆分,然后将值设置到日历对象中,这样可以解决问题,但这真的让我疯了!! - Vivek

2
一个简单的方法是交换字母。
String s = "16-05-2011 02:00:00";
String newDate=s.substring(6,10)+s.substring(3,6)+'-'+s.substring(0,2)+s.substring(10);

0

当您想要输出格式化的日期时,需要使用格式化程序。

public static void main(String[] args) throws ParseException {
    String oldScheduledDate = "16-05-2011 02:00:00";
    DateFormat oldFormatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date oldDate = (Date)oldFormatter .parse(oldScheduledDate);
    System.out.println(formatter.format(oldDate));
}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接