Java Date Format Examples

How to compare dates in java
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
package basics;
 
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class DateExamples {
 
public static void main(String[] args) {
 System.out.println(DateExamples.isDateGreaterThanToday("2/07/2010"));
}
 
public static boolean isDateGreaterThanToday(String date) {
 boolean results = true;
 
 DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
 if (date != null && !date.trim().equals("")) {
  try {
   Date dateToBeCompared = dateFormat.parse(date);
   Date today = new Date();
   if (today.compareTo(dateToBeCompared) > 0) {
    results = false;
   }
  } catch (ParseException e) {
   e.printStackTrace();
   results = true;
  }
 }
 return results;
}
}

2.How to format date in java
SymbolMeaningPresentationExample
Gera designatorTextAD
yyearNumber2009
Mmonth in yearText & NumberJuly & 07
dday in monthNumber10
hhour in am/pm (1-12)Number12
Hhour in day (0-23)Number0
mminute in hourNumber30
ssecond in minuteNumber55
SmillisecondNumber978
Eday in weekTextTuesday
Dday in yearNumber189
Fday of week in monthNumber2 (2nd Wed in July)
wweek in yearNumber27
Wweek in monthNumber2
aam/pm markerTextPM
khour in day (1-24)Number24
Khour in am/pm (0-11)Number0
ztime zoneTextPacific Standard Time
'escape for textDelimiter(none)
'single quoteLiteral'

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
package basics;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class DateFormatExample {
 
public static void main(String[] args) {
 
SimpleDateFormat formatter = null;
Date date = new Date();
 
formatter = new SimpleDateFormat("MM/dd/yy");
String s = formatter.format(date); // Example 07/02/10
 
System.out.println(s);
 
formatter = new SimpleDateFormat("dd-MMM-yy");
s = formatter.format(date);// 02-Jul-10
System.out.println(s);
 
formatter = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
s = formatter.format(date); // 2010.07.02.21.32.35
System.out.println(s);
 
formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
s = formatter.format(date); // Fri, 02 Jul 2010 21:32:35 +0800
System.out.println(s);
 
formatter.applyPattern("EEE, MMM d, ''yy");
s = formatter.format(date); // Fri, Jul 2, '10
System.out.println(s);
 
formatter.applyPattern("hh 'o''clock' a, zzzz");
s = formatter.format(date); // 09 o'clock PM, Singapore Time
System.out.println(s);
 
formatter.applyPattern("yyyy.MMMMM.dd GGG hh:mm aaa");
s = formatter.format(date); // 2010.July.02 AD 09:39 PM
System.out.println(s);
}
}


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email