简体   繁体   English

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

[英]java string to datetime conversion issue

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/28/2006
01/16/2007 01/16/2007
Tue Apr 01 00:00:00 PDT 2008 2008 年 4 月 1 日星期二 00:00:00 PDT
Tue Apr 01 00:00:00 PDT 2008 2008 年 4 月 1 日星期二 00:00:00 PDT
done完毕

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");
      }
    }
"dd/MM/yyyy"

应该读:

"MM/dd/yyyy"

正如彼得所提到的,字母的含义可以在这里的文档中找到: https : //docs.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html

The reason that it wasn't giving you what you expected is like Peter said the SimpleDateFormat should read "MM/dd/yyyy"它没有给你你期望的原因就像彼得说SimpleDateFormat应该读为"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 .结果表明它们似乎相等的原因是因为使用您给它的格式"dd/MM/yyyy"d1String的月份是 28。它需要 28 - 12,加上一年, 16 - 12,再加一年,结果是 4(四月),现在是 2008 年。 d2String

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM