Search code examples
javadateunix-timestamp

How to convert Formatted Date (yyyy-MM-dd) to Unix time in Java?


How to convert Formatted date (yyyy-MM-dd) to Unix time in Java?

I want to declare a date using

    Date birthday = new Date(y_birthday, m_birthday, d_birthday);

but this constructor has been deprecated, so I got to use the other constructor which uses Unix timestamp


Solution

  • So, you have the date as a string in the format yyyy-MM-dd? Use a java.text.SimpleDateFormat to parse it into a java.util.Date object:

    String text = "2011-12-12";
    
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    Date date = df.parse(text);
    

    edit If you need a java.sql.Date, then you can easily convert your java.util.Date to a java.sql.Date:

    java.sql.Date date2 = new java.sql.Date(date.getTime());