Creating UTC time in java

I want to get the UTC time for 01/01/2100 in Java before '2100-01-01 00:00:00'. I get the "2100-01-01 00:08:00". Any idea how to fix this.

public Date getFinalTime() {
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    Date finalTime = null;

    try
    {
        finalTime = df.parse("01/01/2100");            
    } catch (ParseException e)
    {
        e.printStackTrace();
    }

    calendar.setTime(finalTime);
    return calendar.getTime();
}
+5
source share
2 answers

You also need to specify the time zone for SimpleDateFormat - currently it is parsing midnight local time, which ends from 8:00 UTC.

TimeZone utc = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(utc);

DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.setTimeZone(utc);
Date finalTime = null;

try
{
    finalTime = df.parse("01/01/2100");            
} catch (ParseException e)
{
    e.printStackTrace();
}

calendar.setTime(finalTime);

Be that as it may, I personally would recommend using Joda Time , which is much more capable of working. I would be happy to translate your example into Joda Time if you want.

, , calendar.getTime() - , finalTime, .

, ParseException , , . , , . , - - , , , Calendar . (, , Joda Time.)

+9

SimpleDateFormat, .

, , . , (, , , ..), .

+2

All Articles