0

how to I convert date time to others time zone using java.

example : 11 June 2021 20:00 to 11 June 2021 06:00 PM

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date parsed = format.parse("2021-03-01 20:00");
*\\to//*
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm z");
Date parsed = format.parse("2021-03-01 06:00 PM");

like this

  • 1
    I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `ZonedDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Dec 03 '20 at 17:33
  • Does this answer your question? [Converting UTC dates to other timezones](https://stackoverflow.com/questions/6088778/converting-utc-dates-to-other-timezones) – Ole V.V. Dec 03 '20 at 17:38
  • Under that other question I wrote [a new and modern answer for you here](https://stackoverflow.com/a/65131306/5772882). – Ole V.V. Dec 03 '20 at 17:47

4 Answers4

1

First of all you should use the new java 8 API for data and time, java.time, secondly you need to have a zone to convert to and from. Here I have assumed you want to use the zone of the device (and convert to GMT) as from and GMT as to.

String input = "2021-03-01 20:00";
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(ZoneId.systemDefault());
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd h:mm a").withZone(ZoneId.of("GMT"));

TemporalAccessor date = inputFormatter.parse(input);
String output = outputFormatter.format(date);
System.out.println(output);
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
1

Joakim Danielson is on to the right thing in his answer: use java.time, the modern Java date and time API, for your date and time work. My solution roughly follows the same overall pattern. There are some details I’d like to show you.

private static final DateTimeFormatter inputFormatter
        = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
private static final DateTimeFormatter outputFormatter
        = DateTimeFormatter.ofPattern("yyyy-MM-dd h:mm a");

DateTimeFormatter is thread-safe so there’s no problem instantiating them only once even if they are used from different threads.

    String input = "2021-03-01 20:00";

    String output = LocalDateTime.parse(input, inputFormatter)
            .atZone(ZoneId.systemDefault())
            .withZoneSameInstant(ZoneOffset.UTC)
            .format(outputFormatter);
    System.out.println(output);

Output is the same as from Joakim’s code. In my time zone (Europe/Copenhagen) it is:

2021-03-01 7:00 PM

java.time lends itself well to a fluent writing style. Why not exploit it? Since conversion to a different time zone was the point, I prefer to make it explicit in the code. The withZoneSameInstant() call makes the conversion. And I prefer to parse into either LocalDateTime or ZonedDateTime rather than using the low-level TemporalAccessor interface directly. The documentation of the interface says:

This interface is a framework-level interface that should not be widely used in application code. Instead, applications should create and pass around instances of concrete types, such as LocalDate. There are many reasons for this, part of which is that implementations of this interface may be in calendar systems other than ISO. …

I need api 21 support. This is not available on api 21

Indeed java.time works nicely on Android API level 21.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

You must get your date format to a specific zone, as you have not mentioned in the post, i will give 1 sample below,

SimpleDateFormat simpleDateFormat = new SimpleDateFormat(yyyy-MM-dd HH:mm);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

Now using this simpleDateFormat for your specific timezone, you can format the value.

Saravanan
  • 7,637
  • 5
  • 41
  • 72
0

The key to the solution is to get the zone offset between two date-times which you can calculate with Duration#between and then change the zone offset of the first date-time into that of the second one (which is equal to the hours and minutes part of the calculated duration.

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // Given date-time strings
        String strOne = "11 June 2021 20:00";
        String strTwo = "11 June 2021 06:00 PM";

        // Respective formatters
        DateTimeFormatter dtfOne = DateTimeFormatter.ofPattern("dd MMMM uuuu HH:mm", Locale.ENGLISH);
        DateTimeFormatter dtfTwo = DateTimeFormatter.ofPattern("dd MMMM uuuu hh:mm a", Locale.ENGLISH);

        // Respective instances of LocalDateTime
        LocalDateTime ldtOne = LocalDateTime.parse(strOne, dtfOne);
        LocalDateTime ldtTwo = LocalDateTime.parse(strTwo, dtfTwo);

        // Duration between the two date-times
        Duration duration = Duration.between(ldtOne, ldtTwo);
        int hours = duration.toHoursPart();
        int minutes = duration.toMinutesPart();

        // Zone offset with hours and minutes of the duration
        ZoneOffset zoneOffset = ZoneOffset.ofHoursMinutes(hours, minutes);

        //
        ZonedDateTime zdt = ldtOne.atZone(ZoneId.systemDefault())   // ZonedDateTime using JVM's time zone
                                .withZoneSameInstant(zoneOffset);   // ZonedDateTime using the given zone offset
        System.out.println(zdt);
        String formatted = zdt.format(dtfTwo);// Format the given ZonedDateTime using the given formatter
        System.out.println(formatted);
    }
}

The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API. Learn more about the modern date-time API at Trail: Date Time.

Note: If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110