Creating Time Stamp in Java

Here is a quick reference for creating time stamp in Java using SimpleDateFormat. The example comes from Konstantina Dimtsa’s snippet on Java Code Geeks. Please refer to the original post for more details.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.javacodegeeks.corejava.text;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class SimpleDateFormatExample {
public static void main(String[] args) {
Date curDate = new Date();
SimpleDateFormat format = new SimpleDateFormat();
String DateToStr = format.format(curDate);
System.out.println("Default pattern: " + DateToStr);
format = new SimpleDateFormat("yyyy/MM/dd");
DateToStr = format.format(curDate);
System.out.println(DateToStr);
format = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
DateToStr = format.format(curDate);
System.out.println(DateToStr);
format = new SimpleDateFormat("dd MMMM yyyy zzzz", Locale.ENGLISH);
DateToStr = format.format(curDate);
System.out.println(DateToStr);
format = new SimpleDateFormat("MMMM dd HH:mm:ss zzzz yyyy",
Locale.ITALIAN);
DateToStr = format.format(curDate);
System.out.println(DateToStr);
format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
DateToStr = format.format(curDate);
System.out.println(DateToStr);
try {
Date strToDate = format.parse(DateToStr);
System.out.println(strToDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
}