How to turn a string into date in Java
Recently, when developing JSON data deserialized into Java objects, it was found that spring MVC and Jackson were not particularly good for date type support, although it provided handy annotations in the process of serializing a Java object to JSON data, but the deserialization did not. This leads to the question that I need to manually convert the string to date type data, and Java.text.SimpleDateFormat provides us with the infrastructure for this transformation. a simple definition of the format pattern listed below, if ' M ' is greater than or equal to 3 bits, the month is displayed as a letter, otherwise it is a number. Refer to Java.text.SimpleDateFormat JavaDoc for more detailed definitions.
Letter Description examplesy M Month in year one, 7 D day in Month 1-31E Day name in week Friday, Sundaya am/pm marker am, PMH Hour in day< c18/>0-23H Hour in AM/pm 1-12m Minute in Hour 0-60s Second in minute 0-60
1. Date = 7-nov-2015SimpleDateFormat Formatter=NewSimpleDateFormat ("dd-mmm-yyyy"); String dateinstring= "7-nov-2015"; Try{Date Date=Formatter.parse (dateinstring); SYSTEM.OUT.PRINTLN (date); System.out.println (Formatter.format (date)); } Catch(ParseException e) {e.printstacktrace (); } Outputmon Nov00:00:00 MYT 201507-nov-20152. Date = 07/06/2015SimpleDateFormat Formatter=NewSimpleDateFormat ("dd/mm/yyyy"); String dateinstring= "07/06/2015"; Try{Date Date=Formatter.parse (dateinstring); SYSTEM.OUT.PRINTLN (date); System.out.println (Formatter.format (date)); } Catch(ParseException e) {e.printstacktrace (); } Outputmon Nov00:00:00 MYT 201507/06/20153. Date = Nov 7, 2015SimpleDateFormat Formatter=NewSimpleDateFormat ("MMM dd, yyyy"); String dateinstring= "Nov 7, 2015"; Try{Date Date=Formatter.parse (dateinstring); SYSTEM.OUT.PRINTLN (date); System.out.println (Formatter.format (date)); } Catch(ParseException e) {e.printstacktrace (); }outputmon Nov00:00:00 MYT 2015Nov07, 20154. Date = Fri, Nov 7 2015SimpleDateFormat Formatter=NewSimpleDateFormat ("E, MMM dd yyyy")); String dateinstring= "Fri, Nov 7 2015"; Try{Date Date=Formatter.parse (dateinstring); SYSTEM.OUT.PRINTLN (date); System.out.println (Formatter.format (date)); } Catch(ParseException e) {e.printstacktrace (); } Outputmon Nov00:00:00 MYT 2015Mon, Nov07 2015 2. Date and Time Example1. Date and time = Friday, Nov 7, 2015 12:10:56PM SimpleDateFormat Formatter=NewSimpleDateFormat ("eeee, MMM dd, yyyy HH:mm:ss a"); String dateinstring= "Friday, Nov 7, 12:10:56 PM"; Try{Date Date=Formatter.parse (dateinstring); SYSTEM.OUT.PRINTLN (date); System.out.println (Formatter.format (date)); } Catch(ParseException e) {e.printstacktrace (); } Outputmon Nov12:10:56 MYT 2015Monday, Nov, 12:10:56 PM
Summarize
This article briefly summarizes the main methods of converting strings to Java objects, and we hope to help you.
How to turn a string into date in Java