简体   繁体   中英

How to convert date in string with or without time into DATE

I have a date in string format like "2017-11-16" or "2017-11-16 12:59:11.243". I have to convert it to Date.

Below is my code:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.sss");
Date createdOn = formatter.parse(date); 

It works fine when the date is "2017-11-16 12:59:11.243". But not able to format with "2017-11-16" date.

String date is coming from URL, so it could be either with time or without time. How can I convert it into Date in spite of the fact what type of date is coming from URL?

Actually, I have to find row from the database based on the date. In the database, the date is storing in the format like 2017-11-16 12:59:11.243. But If from URL 2017-11-16 is coming then it should find according to this date.

You can modify the pars based on the presence of time,

if(dateOrDataTime.contains(":")){
  //Use parser with date-time. & fetch with equal
}else{
  //Use parser for date only. & fetch using date(date_time)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM