Date and Time formatting Cheat Sheet
Symbol | Meaning | Type |
Type |
G | Era | Text |
GG->AD |
Y | Year | Number |
yy -> 03, yyyy -> 2003 |
M | Month | Text or Number |
M -> 7, MM -> 07, MMM -> Jul , MMMM -> July |
d | Day in month | Number |
d -> 3 , dd -> 03 |
h | Hour (1-12, AM/PM) | Number |
h -> 3 , hh -> 03 |
H | Hour (0-23) | Number |
H -> 15 , HH -> 15 |
k | Hour (1-24) | Number |
k -> 3 , kk -> 03 |
K | Hour (0-11 AM/PM) | Number |
K -> 15 , KK -> 15 |
m | Minute | Number |
m -> 7 , m -> 15 , mm -> 15 |
s | Second | Number |
s -> 15 , ss -> 15 |
S | Millisecond (0-999) | Number |
SSS -> 007 |
E | Day in week | Text |
EEE -> Tue , EEEE -> Tuesday |
D | Day in yr(1-365,1-364) | Number |
D -> 65 , DDD -> 065 |
F | Day of week in month (1-5)| | Number |
F -> 1 |
w | Week in year (1-53) | Number |
w -> 7 |
a | AM/PM | Text |
a -> AM , aa -> AM |
z | Time zone | Text |
z -> EST , zzz -> EST , zzzz -> Eastern Standard Time |
Some sample of date format
String DATE_FORMAT_1 = "dd-MMM-yyyy kk:mm";
String DATE_FORMAT_2 = "yyyy-MM-dd HH:mm:ss";
String DATE_FORMAT_3 = "yyyy-MM-dd";
String DATE_FORMAT_4 = "dd-MMM-yyyy";
String DATE_FORMAT_5 = "dd_MM_yyyy";
String DATE_FORMAT_6 = "yyyy-MM-dd'T'HH:mm:ss";
String DATE_FORMAT_7 = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'";
1. Get today date.
Example - 1
public String getCurrentTimeStr() {
return new SimpleDateFormat(DATE_FORMAT_1, Locale.US).format(new Date())
}
2. Compare dates.
Example - 2
public boolean isFutureDate(String originalDate) {
boolean isFuture = false;
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_1, Locale.US); Date dateObj;
try {
dateObj = sdf.parse(originalDate);
if (new Date().before(dateObj)) {
isFuture = true;
}
} catch (ParseException e) {
}
return isFuture
}
3. Convert UTC to Local date UTC is the common time standard across the world.
Example - 3
public String convertUtcToLocal(String dateTime) {
String do = "";
if(dateTime !=null){
DateFormat originalFormat = new SimpleDateFormat(DATE_FORMAT_2, Locale.US);
originalFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
DateFormat targetFormat = new SimpleDateFormat(DATE_FORMAT_2, Locale.US);
targetFormat.setTimeZone(TimeZone.getDefault())
try {
Date date = originalFormat.parse(dateTime);
dob = targetFormat.format(date);
} catch (ParseException e) {
}
}
return do;
}
4. Merge Date and time
private static final String DATE_TIME = "d MMM yyyy HH:mm";
Example - 4
public Date getTrainStartTime(String originalDate, String time) {
String mAlertDateTime = originalDate + " " + time;
SimpleDateFormat dft = new SimpleDateFormat(DATE_TIME, Locale.getDefault());
try {
Date d = dft.parse(mAlertDateTime);
return d;
} catch (ParseException e) {
e.printStackTrace();
}
return new Date();
}