I have a scenario where my input is yyyy-MM-dd
and output should be yyyy-MM-dd HH:mm:ss.SSS
in java. Example: 2022-03-15
as input, My expected O/P : 2022-03-15 12:00:12.000
CodePudding user response:
yyyy-MM-dd
is effectivly a LocalDate. What you're trying to do is convert it to LocalDateTime.
From howtodoinjava.com
You could either set the time to 00:00
with
LocalDate localDate = LocalDate.parse("2019-01-04");
//Beginning of the day
LocalDateTime localDateTime1 = localDate.atStartOfDay();
System.out.println(localDateTime1);
Use the current time with
//Current time
LocalDateTime localDateTime2 = localDate.atTime(LocalTime.now());
System.out.println(localDateTime2);
Or add the 12:00:12.000
with
//Specific time
LocalDateTime localDateTime3 = localDate.atTime(12, 12, 000);
System.out.println(localDateTime3);
Note that you always need the first line of code
LocalDate localDate = LocalDate.parse("2019-01-04");
To format it in a specific way, use SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String formatedDate = sdf.format(localDate);
CodePudding user response:
You can achieve that by using the following function:
LocalTime myTime = LocalTime.parse("12:00:12.000");
LocalDateTime myDateTime = LocalDateTime.of(myInputDate, myTime);
and myDateTime
will output: 2022-03-15T12:00:12