繁体   English   中英

从毫秒转换为MYSQL日期

[英]Convert from milliseconds to MYSQL 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提前...... :)

我们将日期或时间戳存储为数据库中的String 因此,以特定格式保存是没有意义的。 您只需将它们保存为SQL Timestamp ,然后在需要显示或需要它们的字符串表示时,使用日期格式函数(无论是在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类型,或者使用上面相同的代码将其首先转换为Timestamp

日期对象没有格式。 这就是我们需要DateFormat对象来格式化它们的原因。

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

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

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'将根据您的需要提供格式的日期。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM