Write a Java program to display combine local datetime in a single object


This Java program combines the current local date and time into a single LocalDateTime object and formats it as a string using DateTimeFormatter.

  • First, the current local date is obtained using the LocalDate.now() method and formatted as a string in the pattern "yyyy-MMM-dd" using DateTimeFormatter.ofPattern(). The formatted date is assigned to a string variable ld and printed to the console.
  • Next, the current local time is obtained using the LocalTime.now() method and formatted as a string in the pattern "hh:mm:ss a" using DateTimeFormatter.ofPattern(). The formatted time is assigned to a string variable lt and printed to the console.
  • Then, the LocalDate and LocalTime objects are combined into a single LocalDateTime object using the LocalDateTime.of() method. The resulting LocalDateTime object is then formatted as a string in the pattern "yyyy-MMM-dd hh:mm:ss a" using DateTimeFormatter.ofPattern(). The formatted date and time are assigned to a string variable ldt and printed to the console.

Overall, this program is useful for combining and formatting local date and time information, which can be useful for various applications that require both date and time information.

Source Code

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
 
class Combine_Local_DateTime
{
    public static void main(String[] args)
	{                       
        LocalDate local_d = LocalDate.now();
        String ld = local_d.format(DateTimeFormatter.ofPattern("yyyy-MMM-dd"));
        System.out.println("Local Date = " + ld);        
        LocalTime local_t = LocalTime.now();
        String lt = local_t.format(DateTimeFormatter.ofPattern("hh:mm:ss a"));
        System.out.println("Local Time = " + lt);        
        LocalDateTime local_dt = LocalDateTime.of(local_d, local_t);        
        String ldt = local_dt.format(DateTimeFormatter.ofPattern("yyyy-MMM-dd hh:mm:ss a"));
        System.out.println("Combine Local Date Time = " + ldt);
    }    
}

Output

Local Date = 2022-Nov-05
Local Time = 12:47:05 PM
Combine Local Date Time = 2022-Nov-05 12:47:05 PM

Example Programs