Java: to Get Current India Time [Duplicate]

I am not able to get current india time.

I want to get current time for india, i updated my system clock after 5 minute then current time, so my system clock is running 5 minute earlier than actual india time but i want to get standard time for india.

current time is 11:05:06 and machine time is 11:10:06

public class TestDate {

    public static void main(String[] args) {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
        Date date = new Date();
        sd.setTimeZone(TimeZone.getTimeZone("IST"));
        System.out.println(sd.format(date));
    }
}

output : 2019.02.12 AD at 11:10:06 IST
expected : 2019.02.12 AD at 11:05:06 IST

but i am getting wrong output , so please suggest

8

The Date API has been superseded by a new JodaTime-like API in Java 8.
Use a ZonedDateTime object.

final ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));

This will give you the output 2019-02-11T14:49:28.625+05:30[Asia/Kolkata]

To format a Temporal use a DateTimeFormatter.

DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                 .format(now);
8

UTC+05:30

This is not a timezone, it's just an offset. You need to use valid timezone in order to print the date in that timezone, e.g.: Asia/Kolkata.

Following should work:

public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
    SimpleDateFormat gmtDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    gmtDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
    //Current Date Time in GMT
    System.out.println("Current Date and Time in UTC time zone: " + gmtDateFormat.format(new Date()));
}

Also, Asia/Kolkata timezone is not always UTC+05:30, it depends on daylight saving. So, we should rather use timezone by name than offset.

1
David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest