Set Date patterns with SimpleDateFormat in Java

Java 8Object Oriented ProgrammingProgramming

The following pattern letters are defined (all other characters from 'A' to 'Z' and from 'a' to 'z' are reserved) for Date and Time in Java

Reference − Oracle Java

LetterDate or Time ComponentPresentationExamples
GEra designatorTextAD
YYearYear1996; 96
YWeek yearYear2009; 09
MMonth in yearMonthJuly; Jul; 07
WWeek in yearNumber27
WWeek in monthNumber2
DDay in yearNumber189
DDay in monthNumber10
FDay of week in monthNumber2
EDay name in weekTextTuesday; Tue
UDay number of week (1 = Monday, ..., 7 = Sunday)Number1
AAm/pm markerTextPM
HHour in day (0-23)Number0
KHour in day (1-24)Number24
KHour in am/pm (0-11)Number0
hHour in am/pm (1-12)Number12
mMinute in hourNumber30
sSecond in minuteNumber55
SMillisecondNumber978
zTime zoneGeneral time zonePacific Standard Time; PST; GMT-08:00
ZTime zoneRFC 822 time zone-800
XTime zone

The above pattern letters are combined to format the date and time. For example −

dd/MM/yyyy
dd-MM-yyyy
MM/dd/yyyy
yyyy-MM-dd

The following is another example −

Example

 Live Demo

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo {
   public static void main(String[] args) throws Exception {
      String pattern = "MM/dd/yyyy";
      SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
      Date dt = dateFormat.parse("22/11/2018");
      System.out.println(dateFormat.format(new Date()));
   }
}

Output

11/22/2018
raja
Published on 19-Dec-2018 06:30:23
Advertisements