【问题标题】:String (dd-MM-yyyy HH:mm) to Date (yyyy-MM-dd HH:mm) | Java字符串 (dd-MM-yyyy HH:mm) 到日期 (yyyy-MM-dd HH:mm) |爪哇
【发布时间】:2010-12-22 17:38:38
【问题描述】:

我在“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,这是完全错误的,我在这里做错了什么?

【问题讨论】:

    标签: java


    【解决方案1】:
        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,但尚未测试确认。
    • 返回类型是String,而我们需要Date。该怎么做?
    • Date 是一样的,不同的是格式 oldFormat = newFormat
    【解决方案2】:

    “yyyy-MM-dd”看起来甚至与“16-05-2011”不一样。唔。那么,为什么不呢?

    提示:

    1. DateFormat 非常直接。它采用指定的格式并使用它——没什么特别的。
    2. 流程:输入日期字符串->转换(带输入格式)->日期->转换(带输出格式)->输出日期字符串
    3. 帖子中的代码包含输出格式,但没有导入格式。

    【讨论】:

    • 我不知道,另一种选择是我将字符串拆分,然后将值设置为日历对象,这样可以解决问题,但这真的让我抓狂!!
    【解决方案3】:

    一种简单的方法是交换字母。

    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);
    

    【讨论】:

      【解决方案4】:

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

      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));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-08
        • 1970-01-01
        • 2012-07-15
        • 2015-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多