java字符串到日期时间的转换问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/746259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:01:06  来源:igfitidea点击:

java string to datetime conversion issue

javastringdatetime

提问by Gern Blanston

I can't seem to see the problem with the example code below. For some reason seems to be ignoring the year and saying the dates are the same, as can be seen in the output below. I must be missing something simple.

我似乎看不到下面示例代码的问题。出于某种原因,似乎忽略了年份并说日期相同,如下面的输出所示。我一定错过了一些简单的东西。

01/28/2006
01/16/2007
Tue Apr 01 00:00:00 PDT 2008
Tue Apr 01 00:00:00 PDT 2008
done

01/28/2006
01/16/2007
星期二 01 00:00:00 PDT 2008
星期二 01 00:00:00 PDT 2008
完成

import java.util.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

    class ExampleProgram {
      public static void main(String[] args){
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        String d1String = "01/28/2006";
        String d2String = "01/16/2007";
        System.out.println(d1String);
        System.out.println(d2String);
        Date d1=null;
        try {
            d1 = df.parse(d1String);
        } catch (ParseException e) {                
            System.out.println(e.getMessage());
        }           
        Date d2=null;
        try {
            d2 = df.parse(d2String);
        } catch (ParseException e) {                
            System.out.println(e.getMessage());
        }
        System.out.println(d1);
        System.out.println(d2);
        System.out.println("done");
      }
    }

采纳答案by Peter

"dd/MM/yyyy"

should read:

应该读:

"MM/dd/yyyy"

回答by Nico Heid

as Peter mentioned, the meaning of the letters can be found in the documentation here: http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html

正如彼得提到的,字母的含义可以在这里的文档中找到:http: //java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html

回答by aintnoprophet

You could try declaring your dates as Dateobjects.

您可以尝试将日期声明为Date对象。

回答by Jeremy Cron

The reason that it wasn't giving you what you expected is like Peter said the SimpleDateFormatshould read "MM/dd/yyyy"

The reason that the result is saying that they appear to be equal is because with the format that you've given it "dd/MM/yyyy", d1String's Month is 28. It is taking 28 - 12, adding a year, 16 - 12, adding another year, and the result is 4 (April) and the year is now 2008. Same thing for d2String.

它没有给你你期望 的原因就像彼得说SimpleDateFormat应该读"MM/dd/yyyy"

结果是说它们看起来相等的原因是因为按照你给它的格式"dd/MM/yyyy"d1String's Month 是 28。它需要 28 - 12,加上一年,16 - 12,再加一年,结果是 4(四月),现在是 2008 年。 . 同样的事情d2String