We could convert a date or time to a specific formatted string, and/or change the timezone, by using SimpleDateFormat
First create a new SimpleDateFormat by passing the specific format. The specific format is combination of defined letters (case sensitive). e.g. y for year, M for month and d for day etc
When forming the pattern, punctuation could be used to make the patterns more desirable, e.g. yyyy-MM-dd:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); String myFormatDate = simpleDateFormat.format(date);
We can also use the setTimeZone to change the timezone of the date:
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
See the whole program:
import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; public class MainClass { public static void main(String[] args) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); String myFormatDate = simpleDateFormat.format(date); System.out.println("Formatted time: " + myFormatDate); simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); myFormatDate = simpleDateFormat.format(date); System.out.println("Formatted time with seconds and mini-seconds: " + myFormatDate); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Australia/Sydney")); myFormatDate = simpleDateFormat.format(date); System.out.println("Formatted time with seconds and mini-seconds on Sydney timezone: " + myFormatDate); } }
Sample output:
Formatted time: 2022-05-04
Formatted time with seconds and mini-seconds: 2022-05-04T14:54:17.393-0700
Formatted time with seconds and mini-seconds on Sydney timezone: 2022-05-05T07:54:17.393+1000