How to compare dates in java
2.How to format date 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
| Symbol | Meaning | Presentation | Example |
|---|---|---|---|
| G | era designator | Text | AD |
| y | year | Number | 2009 |
| M | month in year | Text & Number | July & 07 |
| d | day in month | Number | 10 |
| h | hour in am/pm (1-12) | Number | 12 |
| H | hour in day (0-23) | Number | 0 |
| m | minute in hour | Number | 30 |
| s | second in minute | Number | 55 |
| S | millisecond | Number | 978 |
| E | day in week | Text | Tuesday |
| D | day in year | Number | 189 |
| F | day of week in month | Number | 2 (2nd Wed in July) |
| w | week in year | Number | 27 |
| W | week in month | Number | 2 |
| a | am/pm marker | Text | PM |
| k | hour in day (1-24) | Number | 24 |
| K | hour in am/pm (0-11) | Number | 0 |
| z | time zone | Text | Pacific Standard Time |
| ' | escape for text | Delimiter | (none) |
| ' | single quote | Literal | ' |
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/10System.out.println(s);formatter = new SimpleDateFormat("dd-MMM-yy");s = formatter.format(date);// 02-Jul-10System.out.println(s);formatter = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");s = formatter.format(date); // 2010.07.02.21.32.35System.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 +0800System.out.println(s);formatter.applyPattern("EEE, MMM d, ''yy");s = formatter.format(date); // Fri, Jul 2, '10System.out.println(s);formatter.applyPattern("hh 'o''clock' a, zzzz");s = formatter.format(date); // 09 o'clock PM, Singapore TimeSystem.out.println(s);formatter.applyPattern("yyyy.MMMMM.dd GGG hh:mm aaa");s = formatter.format(date); // 2010.July.02 AD 09:39 PMSystem.out.println(s);}} |
Posted in: