Java: Display the dates in the specified formats
Java DateTime, Calendar: Exercise-24 with Solution
Write a Java program to display dates in the following formats.
Sample format:
Default format of LocalDate=2016-09-16 16::Sep::2016 Default format of LocalDateTime=2016-09-16T11:46:01.455 16::Sep::2016 11::46::01 Default format of Instant=2016-09-16T06:16:01.456Z Default format after parsing = 2014-04-27T21:39:48
Sample Solution:
Java Code:
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateParseFormatExercise24 {
public static void main(String[] args) {
//Format examples
LocalDate date = LocalDate.now();
//default format
System.out.println("\nDefault format of LocalDate="+date);
//specific format
System.out.println(date.format(DateTimeFormatter.ofPattern("d::MMM::uuuu")));
LocalDateTime dateTime = LocalDateTime.now();
//default format
System.out.println("Default format of LocalDateTime="+dateTime);
//specific format
System.out.println(dateTime.format(DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss")));
Instant timestamp = Instant.now();
//default format
System.out.println("Default format of Instant="+timestamp);
//Parse examples
LocalDateTime dt = LocalDateTime.parse("27::Apr::2014 21::39::48",
DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss"));
System.out.println("Default format after parsing = "+dt+"\n");
}
}
Sample Output:
Default format of LocalDate=2017-06-21 21::Jun::2017 Default format of LocalDateTime=2017-06-21T11:46:21.543 21::Jun::2017 11::46::21 Default format of Instant=2017-06-21T06:16:21.543Z Default format after parsing = 2014-04-27T21:39:48
N.B.: The result may varry for your system date and time.
Pictorial Presentation:
Flowchart:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Java program to get the months remaining in the year.
Next: Write a Java program to get the information of current/given year.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-exercises/datetime/java-datetime-exercise-24.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics