Get date and time by zone in Java

In this source code example, we show you how to get date and time by zone in Java using Java 8 ZonedDateTime class.

Get the date and time by zone in Java

package com.ramesh.java8.datetime;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
 * Useful Java8DateUtiliy Methods
 * @author javaguides.net
 *
 */

public final class Java8DateUtility {
    /**
     * Get date and time by zone.
     * @param timeZone
     * @return
     */
    public static ZonedDateTime timeZone(String timeZone) {
        ZoneId america = ZoneId.of(timeZone);
        LocalDateTime localtDateAndTime = LocalDateTime.now();
        ZonedDateTime dateAndTimeInNewYork = ZonedDateTime.of(localtDateAndTime, america);
        System.out.println("Current date and time in a particular timezone : " + dateAndTimeInNewYork);
        return dateAndTimeInNewYork;
    } 
}

JUnit test case

package com.ramesh.java8.datetime;
import org.junit.Test;

/**
 * JUnit test cases for Java8DateUtiliy Methods
 * @author javaguides.net
 *
 */
public class Java8DateUtilityTest {
    @Test
    public void timeZoneTest() {
        System.out.println("America/Los_Angeles Zone :: " + Java8DateUtility.timeZone("America/Los_Angeles"));
    }
}
Run the JUnit test cases will print the output:
America/Los_Angeles Zone :: 2018-07-21T18:40:51.693-07:00[America/Los_Angeles]


Comments