Java.util.Calendar - milliseconds since Jan 1, 1970

后端 未结 6 2131
梦毁少年i
梦毁少年i 2021-01-05 02:03

Program followed by output. Someone please explain to me why 10,000,000 milliseconds from Jan 1, 1970 is November 31, 1969. Well, someone please explain what\'s wrong with

6条回答
  •  南方客
    南方客 (楼主)
    2021-01-05 02:51

    First, c.get(Calendar.MONTH) returns 0 for Jan, 1 for Feb, etc.

    Second, use DateFormat to output dates.

    Third, your problems are a great example of how awkward Java's Date API is. Use Joda Time API if you can. It will make your life somewhat easier.

    Here's a better example of your code, which indicates the timezone:

    public static void main(String[] args) {
    
        final DateFormat dateFormat = SimpleDateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
    
        long l = 10000000L;
        System.out.println("Long value: " + l);
        Calendar c = new GregorianCalendar();
        c.setTimeInMillis(l);
        System.out.println("Date: " + dateFormat.format(c.getTime()));
    
        l = 1000000000000L;
        System.out.println("\nLong value: " + l);
        c.setTimeInMillis(l);
        System.out.println("Date: " + dateFormat.format(c.getTime()));
    }
    

提交回复
热议问题