java date string

www.la‮uttu‬ri.com
java date string

In Java, you can use the java.text.SimpleDateFormat class to parse a string representation of a date and time into a java.util.Date object, and to format a Date object as a string.

Here is an example of how to parse and format a date string in Java using the SimpleDateFormat class:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
  public static void main(String[] args) throws ParseException {
    // Create a SimpleDateFormat instance
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // Parse the date string into a Date object
    String dateString = "2022-12-31 23:59:59";
    Date date = sdf.parse(dateString);
    System.out.println("Date: " + date);  // Output: Date object representing the parsed date

    // Format the Date object as a string
    String formattedDate = sdf.format(date);
    System.out.println("Formatted date: " + formattedDate);  // Output: formatted date string
  }
}

In this example, we create a SimpleDateFormat instance and specify a date and time format string using the yyyy (year), MM (month), dd (day), HH (hour), mm (minute), and ss (second) patterns. We then use the parse method to parse the date string into a Date object, and the format method to format the Date object as a string.

You can modify the format string to suit your needs. For example, you can use the yyyy-MM-dd pattern to specify a date-only format, or the HH:mm pattern to specify a time-only format. Refer to the SimpleDateFormat documentation for a complete list of patterns.

Created Time:2017-11-03 00:14:53  Author:lautturi