date timezone java code example

Example 1: get date by timezone java

Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// Use Madrid's time zone to format the date in
df.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));

System.out.println("Date and time in Madrid: " + df.format(date));

Example 2: java java.util.TimeZone to java.time.ZoneId

package com.javabrahman.java8.time;
import java.time.ZoneId;
import java.util.TimeZone;
public class TimeZoneToZoneId {
  public static void main(String args[]) {
 
    //Converting system's 'default' java.util.TimeZone to java.time.ZoneId
    ZoneId zoneId = TimeZone.getDefault().toZoneId();
    System.out.println("ZoneId from default system TimeZone: " + zoneId);
 
    //Converting custom defined java.util.TimeZone to java.time.ZoneId
    TimeZone timeZoneLA = TimeZone.getTimeZone("America/Los_Angeles");
    ZoneId zoneIdLA = timeZoneLA.toZoneId();
    System.out.println("ZoneId from custom 'LA' TimeZone: " + zoneIdLA);
 
  }
}

Tags:

Java Example