Search code examples
javadatesimpledateformatdate-formatting

How do I set the date to the current day in Korea or anywhere else?


So, I got the time to be in Korean time with this code:

formatClock = new SimpleDateFormat("hh:mm:ss a");
formatClock.setTimeZone(TimeZone.getTimeZone("Asia/Seoul"));

However, how do I set the date to the current day in Korean?

For instance, I want it to output Sunday 7/23/2017.


Solution

  • Old API

    Use another SimpleDateFormat with the desired format, and use java.util.Locale to explicity uses the English names for days of the week:

    SimpleDateFormat sdf = new SimpleDateFormat("EEEE M/dd/yyyy", Locale.ENGLISH);
    sdf.setTimeZone(TimeZone.getTimeZone("Asia/Seoul"));
    System.out.println(sdf.format(new Date()));
    

    The output will be:

    Sunday 7/23/2017

    If you don't specify the locale, it uses the system's default, which is not guaranteed to always be English (and it can also be changed without notice, even at runtime, so it's always better to make it explicit in your code by using a proper Locale, if you always want the days of the week in English - or in any other language).


    Java new Date/Time API

    The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.

    If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.

    If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).

    The code below works for both. The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.

    To get the current date in a timezone, you can use a LocalDate (a date with day/month/year) with a ZoneId (a timezone), and you use a DateTimeFormatter to format it:

    // Korean timezone
    ZoneId zone = ZoneId.of("Asia/Seoul");
    // current date in Korea timezone
    LocalDate currentDateInKorea = LocalDate.now(zone);
    // formatter (use English locale to correctly use English name for day of week)
    DateTimeFormatter fmt = DateTimeFormatter.ofPattern("EEEE M/dd/yyyy", Locale.ENGLISH);
    System.out.println(fmt.format(currentDateInKorea));
    

    The output will be:

    Sunday 7/23/2017


    Note: a java.util.Date itself has no format, it just represents the number of milliseconds since epoch (1970-01-01T00:00Z). What we're doing here is just changing the representation of this value in a specific format, for a specific timezone.