SimpleDateFormat UTC Example

SimpleDateFormat UTC Example

SimpleDateFormat API available in JDK since 1.2 and mostly preferred by the developers to format date in different format. In this example you will how we can format date in UTC format:

  • SimpleDateFormatUTC.java:
package com.javahonk.dateformatter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class SimpleDateFormatUTC {

	public static void main(String[] args) {
		
		String validPatterns1 = "EEE, MMM d, ''yy";
		String validPatterns2 = "h:mm a";
		String validPatterns3 = "YYYY-'W'ww-u";
		String validPatterns4 = "yyyy-MM-dd";
		String validPatterns5 = "yyyy-MM-dd HH:mm:ss";
		
		System.out.println("SimpleDateFormat in UTC format with different pattern: \n");
		
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(validPatterns1);
		simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));		
		System.out.println("EEE, MMM d, ''yy:--> "+simpleDateFormat.format(new Date()));
		
		simpleDateFormat = new SimpleDateFormat(validPatterns2);
		simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
		System.out.println("h:mm a:--> "+simpleDateFormat.format(new Date()));
		
		simpleDateFormat = new SimpleDateFormat(validPatterns3);
		simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
		System.out.println("YYYY-'W'ww-u:--> "+simpleDateFormat.format(new Date()));
		
		simpleDateFormat = new SimpleDateFormat(validPatterns4);
		simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
		System.out.println("yyyy-MM-dd:--> "+simpleDateFormat.format(new Date()));
		
		simpleDateFormat = new SimpleDateFormat(validPatterns5);
		simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
		System.out.println("yyyy-MM-dd HH:mm:ss:--> "+simpleDateFormat.format(new Date()));
	}

}
  • Output:

SimpleDateFormat UTC Example

  • For more information on SimpleDateFormat please visit Oracle API here

Leave a Reply

Your email address will not be published. Required fields are marked *