Let`s see how to output the current time and date in a desired format with SimpleDateFormat
.
SimpleDateFormat is a class that has been used to print dates since before Java8.
Java8 introduced a new class called DateTimeFormatter which has the same behavior as SimpleDateFormat.
Here, we will learn how to output date with SimpleDateFormat.
Print current date and time
You can create a SimpleDateFormat object with a pattern like "yyyy-MM-dd".
If you pass a time object to format()
, it creates a string with the input pattern and returns it.
String pattern = "yyyy-MM-dd";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String date = simpleDateFormat.format(new Date());
System.out.println(date);
result
2020-04-11
Print date and time as StringBuffer
In the example above, format()
returned the result as a String object.
If you want to return a StringBuffer, you can pass a StringBuffer object as an argument to format()
as follows.
StringBuffer stringBuffer = new StringBuffer();
Date now = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
simpleDateFormat.format(now, stringBuffer, new FieldPosition(0));
System.out.println(stringBuffer);
result
2020-04-11 22:40:37+0900
Output as a string in a specific Locale
When outputting dates, you can also output strings in your preferred language.
When creating a SimpleDateFormat object, you can pass a Locale object along with the pattern. If you run the following code, you can see that the date is printed in the language that matches the set Locale.
String pattern = "EEEEE dd MMMMM yyyy HH:mm:ss.SSSZ";
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat(pattern, new Locale("ko", "KR"));
SimpleDateFormat simpleDateFormat2 =
new SimpleDateFormat(pattern, new Locale("en", "US"));
String date = simpleDateFormat.format(new Date());
System.out.println(date);
date = simpleDateFormat2.format(new Date());
System.out.println(date);
result
토요일 11 4월 2020 23:03:48.889+0900
Saturday 11 April 2020 23:03:48.889+0900
When creating a Locale, you need to input the language code and country code in order like Locale(language, country).
Parse the date string
Instead of creating a Date object as a string, you can also convert a string into a Date object.
If you create a SimpleDateFormat object and pass the same string as the pattern as a parse()
argument, a Date object is returned.
String pattern = "yyyy-MM-dd";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
Date date = simpleDateFormat.parse("2018-09-09");
System.out.println(date);
pattern information
The meanings of the alphabets used when creating patterns are as follows:
Pattern | |
---|---|
y | Year |
M | Month in year |
w | Week in year |
W | Week in month |
D | The day count in year |
d | Day of the month |
E | Day name in the week |
a | AM or PM marker |
H | Hour in the day (0-23) |
h | Hour in am/pm for 12 hour format (1-12) |
m | Minute in the hour |
s | Second in the minute |
z | Timezone |
The following are examples of commonly used patterns.
Pattern | Result |
---|---|
MM/dd/yyyy | 01/02/2018 |
dd-M-yyyy hh:mm:ss | 02-1-2018 06:07:59 |
dd MMMM yyyy | 02 January 2018 |
dd MMMM yyyy zzzz | 02 January 2018 India Standard Time |
E, dd MMM yyyy HH:mm:ss z | Tue, 02 Jan 2018 18:07:59 IST |
Reference
Related Posts
- Java - Remove items from List while iterating
- Java - How to find key by value in HashMap
- Java - Update the value of a key in HashMap
- Java - How to put quotes in a string
- Java - How to put a comma (,) after every 3 digits
- BiConsumer example in Java 8
- Java 8 - Consumer example
- Java 8 - BinaryOperator example
- Java 8 - BiPredicate Example
- Java 8 - Predicate example
- Java 8 - Convert Stream to List
- Java 8 - BiFunction example
- Java 8 - Function example
- Java - Convert List to Map
- Exception testing in JUnit
- Hamcrest Collections Matcher
- Hamcrest equalTo () Matcher
- AAA pattern of unit test (Arrange/Act/Assert)
- Hamcrest Text Matcher
- Hamcrest Custom Matcher
- Why Junit uses Hamcrest
- Java - ForkJoinPool
- Java - How to use Futures
- Java - Simple HashTable implementation
- Java - Create a file in a specific path
- Java - Mockito의 @Mock, @Spy, @Captor, @InjectMocks
- Java - How to write test code using Mockito
- Java - Synchronized block
- Java - How to decompile a ".class" file into a Java file (jd-cli decompiler)
- Java - How to generate a random number
- Java - Calculate powers, Math.pow()
- Java - Calculate the square root, Math.sqrt()
- Java - How to compare String (==, equals, compare)
- Java - Calculate String Length
- Java - case conversion & comparison insensitive (toUpperCase, toLowerCase, equalsIgnoreCase)