Letter | Date or Time Component | Presentation | Examples |
---|---|---|---|
G | Era designator | Text | AD |
y | Year | Year | 1996; 96 |
M | Month in year | Month | July; Jul; 07 |
w | Week in year | Number | 27 |
W | Week in month | Number | 2 |
D | Day in year | Number | 189 |
d | Day in month | Number | 10 |
F | Day of week in month | Number | 2 |
E | Day in week | Text | Tuesday; Tue |
a | Am/pm marker | Text | PM |
H | Hour in day (0-23) | Number | 0 |
k | Hour in day (1-24) | Number | 24 |
K | Hour in am/pm (0-11) | Number | 0 |
h | Hour in am/pm (1-12) | Number | 12 |
m | Minute in hour | Number | 30 |
s | Second in minute | Number | 55 |
S | Millisecond | Number | 978 |
z | Time zone | General time zone | Pacific Standard Time; PST; GMT-08:00 |
Z | Time zone | RFC 822 time zone | -0800 |
import java.text.SimpleDateFormat; import java.util.Date; /** * */ /** * @author Dinesh.Rajput * */ public class SimpleDateFormatExample { /** * @param args */ public static void main(String[] args) { //Creating Date in java with today's date. Date todayDate = new Date(); //change date to string on dd-MM-yyyy format e.g. "20-02-2017" SimpleDateFormat dateformater_Java = new SimpleDateFormat("dd-MM-yyyy"); String todayDateStr = dateformater_Java.format(todayDate); System.out.println("Today's date into dd-MM-yyyy format: " + todayDateStr); //converting date to string dd/MM/yyyy format for example "20/02/2017" SimpleDateFormat formatDateJava = new SimpleDateFormat("dd/MM/yyyy"); todayDateStr = formatDateJava.format(todayDate); System.out.println("Today's date into dd/MM/yyyy format: " + todayDateStr); //change date into string yyyyMMdd format example "20170220" SimpleDateFormat dateformater_yyyyMMdd = new SimpleDateFormat("yyyyMMdd"); todayDateStr = dateformater_yyyyMMdd.format(todayDate); System.out.println("Today's date into yyyyMMdd format: " + todayDateStr); } }
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * */ /** * @author Dinesh.Rajput * */ public class SimpleDateFormatExample { /** * @param args */ public static void main(String[] args) { //parse string to date dd/MM/yyyy format e.g. "20-02-2017" SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); try { Date date = formatter.parse("20/02/2017"); System.out.println("Date is: "+date); } catch (ParseException e) { e.printStackTrace(); } //parse string to date dd-MM-yyyy format e.g. "20-02-2017" formatter = new SimpleDateFormat("dd-MM-yyyy"); try { Date date = formatter.parse("20-02-2017"); System.out.println("Date is: "+date); } catch (ParseException e) { e.printStackTrace(); } } }
Labels: Core JAVA, Core Java Interview Questions, interview questions, String in Java