dcsimg
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Tip: Formatting Global Dates in Java

Due to globalization, it is important to understand how each country represents the date. See how to set the date correctly, depending on the target country.


advertisement

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


Dates are an important part of all record keeping activities. Due to globalization, it is important to understand how each country represents the date. Some countries start the date with Year, some with Month and some of them interchange Month and Date place holders. Formatting (using ofPattern() method) is a powerful utility that easily helps users overcome this problem.

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class TimeFormats 
{
public static void main(String args[]) 
{ 
LocalDateTime localDateTime = LocalDateTime.now(); 
System.out.println("Default format: " + localDateTime); 
//Formatting 
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss"); 
String formattedDate = localDateTime.format(dateTimeFormatter); 
System.out.println("After formatting (dd-MMM-yyyy HH:mm:ss): " + formattedDate); 
//Additonal Formatting 
dateTimeFormatter = DateTimeFormatter.ofPattern("E, MMM dd yyyy"); 
formattedDate = localDateTime.format(dateTimeFormatter); 
System.out.println("After formatting (E, MMM dd yyyy): " + formattedDate); 
} 
}

Expected output:

[root@mypc]# java TimeFormats
Default format: 2018-11-27T16:40:07.893
After formatting (dd-MMM-yyyy HH:mm:ss): 27-Nov-2018 16:40:07
After formatting (E, MMM dd yyyy): Tue, Nov 27 2018

 

Visit the DevX Tip Bank

 





   
Sridhar M S. is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.
Thanks for your registration, follow us on our social networks to keep up-to-date