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

↘锁芯ラ 提交于 2020-01-06 14:17:35

问题


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


回答1:


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());



回答2:


Use a calendar object if you want more control of the date object

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2011);
calendar.set(Calendar.MONTH, 11); // indexed month (December)
calendar.set(Calendar.DATE, 12);
Date date = new Date(calendar.getTime().getTime());

The hours, minutes, seconds etc of the current time will be set though so you may want to set those to 0 (manually per field)

If you're using Java 7 then I think there's some much nicer stuff you can use for handling dates



来源:https://stackoverflow.com/questions/8476147/how-to-convert-formatted-date-yyyy-mm-dd-to-unix-time-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!