从毫秒转换为MYSQL日期

时间:2013-07-05 13:36:23

标签: java

您好我需要将毫秒转换为Date。 MYSQL也应该接受日期。

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("US/Central"));
calendar.setTimeInMillis(System.currentTimeMillis());
System.out.println("GregorianCalendar -" + sdf.format(calendar.getTime()));

我试过这个例子但是在这里“sdf.format(calendar.getTime()”这个方法它给出了以下格式的字符串。 “yyyy-MM-dd HH:mm:ss”

但我也希望Date对象也采用上述格式(yyyy-MM-dd HH:mm:ss)。

那么如何将其转换为日期格式。

请帮帮我...

Thanx提前......:)

5 个答案:

答案 0 :(得分:2)

我们将日期或时间戳存储为数据库中的 String 。因此,以特定格式保存是没有意义的。您只需将它们保存为SQL Timestamp,然后使用 Date 格式函数格式化它们(使用 Java 或使用在后端) PL / SQL )只要你需要显示或需要它们的字符串表示。

因此,请使用java.sql.Timestamp作为

Timestamp dbDateTime = new java.sql.Timestamp(System.currentTimeMillis()); // or
Timestamp dbDateTime = new java.sql.Timestamp(calendar.getTimeInMillis());

编辑 如果DOB字段的类型为java.util.Date,则使用

Timestamp dbDateTime = new java.sql.Timestamp(dob.getTime());

如果字段的类型为java.sql.Date,那么如果后端列的类型为DATE,则可以将其保存为原样,或者使用上面相同的代码将其转换为{{1}首先。

答案 1 :(得分:0)

日期对象没有格式。这就是为什么我们需要DateFormat对象来格式化它们。

答案 2 :(得分:0)

实际上,您不能以特定格式拥有日期对象。 Java在内部管理日期对象。但是,您可以使用SimpleDateFormat在需要时格式化日期对象。 顺便说一下,以特定格式使用Date对象毫无意义。

答案 3 :(得分:0)

public static Date getDate(long milliSeconds, String dateFormat)
{
DateFormat formatter = new SimpleDateFormat(dateFormat);

 Calendar calendar = Calendar.getInstance();
 calendar.setTimeInMillis(milliSeconds);
 DateFormat formatter2 = new SimpleDateFormat(dateFormat);
 Date d = null;
try {
    d = (Date)formatter2.parse(formatter.format(calendar.getTime()));
    System.out.println(formatter.format(calendar.getTime()));
} catch (ParseException e) {
    e.printStackTrace();
}
 return d;
}

尝试像这样访问

System.out.println(getDate(82233213123L,“yyyy-MM-dd HH:mm:ss”));

out put应该是8月10日星期四00:03:33 IST 1972

答案 4 :(得分:0)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("US/Central"));
calendar.setTimeInMillis(System.currentTimeMillis());
String date =  sdf.format(calendar.getTime());
Date dateObject = sdf.parse(date);

'dateObject'将根据您的需要为您提供日期。

相关问题