skip to Main Content

I need to convert a Date in java:
Date date=calendar.getTime(); // yyyy-MM-dd
I want to turn it into a String "yyyy-MM-dd HH:mm:ss" so i can insert it into a table in MySQL. Any ideea?

2

Answers


  1. To convert a Date object to a String in the format "yyyy-MM-dd HH:mm:ss", you can use the SimpleDateFormat class in Java.

    import java.util.Calendar;
    import java.util.Date;
    
    public class DateToStringExample {
        public static void main(String[] args) {
            Calendar calendar = Calendar.getInstance();
            Date date = calendar.getTime();
    
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = dateFormat.format(date);
    
            System.out.println("Formatted Date String: " + dateString);
        }
    }
    

    I made an example for you, you first obtain the current date and time using the Calendar class. Then, you create an instance of SimpleDateFormat and specify the desired format pattern as "yyyy-MM-dd HH:mm:ss". Finally, you format the Date object using the format() method of SimpleDateFormat, which returns the formatted date string.

    You can then use the dateString variable to insert the formatted date into a MySQL table

    Login or Signup to reply.
  2. You can use SimpleDateFormat:

     Date date = new Date();
     SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
     String formattedDate = dateFormat.format(date);
    

    or

    Date date = new Date();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    String formattedDate = formatter.format(date.toInstant());
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search