This article is a mirror article of machine translation, please click here to jump to the original article.

View: 13902|Reply: 0

[Source] Conversion of Date and String in Java

[Copy link]
Posted on 1/11/2019 3:19:25 PM | | | |
When we register a website, we often need to fill in personal information, such as name, age, date of birth, etc., when the value of the date of birth on the page is passed to the background, it is a string, and we do need a date type when we store it in the database, in turn, when it is displayed on the page, we need to get the date of birth from the database, at this time the type is the date type, and then we need to convert the date type into a string to display on the page. Java's API provides us with a class called DateForamt that forwards dates and strings to each other. DateForamt is an abstract class, so its subclass SimpleDateFormat is usually used. SimpleDateFormat has 4 constructors, the second is most often used.



The pattern in the constructor is a time mode, and the API explains what pattern it is, as follows



1. Date to string (formatting)

Run the result
2016-10-24
2016-10-24 21:59:06
October 24, 2016 21:59:06


2. String to date (parsing)

Run the result

Mon Oct 24 21:59:06 CST 2016
When converting strings to dates, you need to pay attention to the given pattern must match the given string format, otherwise java.text.ParseException will be thrown, for example, the following one is wrong, the string does not give the time, minutes, seconds, then SimpleDateFormat of course cannot give you the value of the time, minutes, seconds out of thin air

Run error

However, a given pattern is fine if it has fewer strings

Run the result

Mon Oct 24 00:00:00 CST 2016
It can be seen that the time, minute, and second are 0 and are not parsed, which is okay.

3. Enter the date and convert it to milliseconds: use the Date method ()

code

Run screenshot:






Previous:A certain treasure 399 yuan Douyin shooting 106 skills
Next:Silicon Valley, Chuan Zhi Dark Horse and java, Python, big data, php, front-end video tutorials
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com