Is Calendar.getInstance().getTime() ever going to give me a different answer than new Date()?

后端 未结 2 1871
有刺的猬
有刺的猬 2021-02-15 13:23

I\'m trying to consolidate some code that is very messy but I want to make sure I don\'t break things. In some places I see a date created as Calendar.getInstance().getTi

2条回答
  •  孤独总比滥情好
    2021-02-15 13:53

    I think both will return same :

    Calendar.getInstance().getTime() : Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch(January 1, 1970 00:00:00.000 GMT (Gregorian).)").

    new Date() : internally uses System.currentTimeMillis(), Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond. the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.

    I checked like :

    public static void main(String[] args) {
        Date date = new Date();
        Date date1 = Calendar.getInstance().getTime();
    
        System.out.println(date +" = " + date1);
    
    }
    

    Output :

    Wed Aug 15 02:45:15 IST 2012 = Wed Aug 15 02:45:15 IST 2012
    

提交回复
热议问题