简体   繁体   English

Java / Servlet:获取当前的sql.Date

[英]Java/Servlet: get current sql.Date

What I need to do is: 我需要做的是:

1) Get user's locale from request. 1)从请求中获取用户的语言环境。

2) Create new sql.Date object with current date and time, based on user's locale 2)根据用户的语言环境,使用当前日期和时间创建新的sql.Date对象

3) Write it in MySQL db, column type: TIMESTAMP 3)将其写入MySQL db,列类型:TIMESTAMP

What I got is: 我得到的是:

java.util.Locale locale = request.getLocale();

java.text.DateFormat dateFormat =
java.text.DateFormat.getDateTimeInstance(
                        java.text.DateFormat.LONG, java.text.DateFormat.LONG, locale );

java.util.Date date = new java.util.Date();

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

Date is OK, but have a problem with time - always 12:00:00 AM. 日期还可以,但是时间有问题-总是12:00:00 AM。

Any suggestions? 有什么建议么? Is there a more efficient way to do this? 有没有更有效的方法可以做到这一点?

甚至更紧凑的解决方案;)

java.sql.Date timeNow = new Date(Calendar.getInstance().getTimeInMillis());

There is one more simple solution for it. 有一个更简单的解决方案。 use this code to get current date using java.util.Date 使用此代码通过java.util.Date获取当前日期

java.util.Calendar cal = java.util.Calendar.getInstance();
java.util.Date utilDate = cal.getTime();
java.sql.Date sqlDate = new Date(utilDate.getTime());

如果需要时间,则需要java.sql.Timestamp而不是java.sql.Date,并且需要数据库中的timestamp列。

请注意, request.getLocale使用的是Accept-Language标题的值,可能并不总是为您提供正确的语言环境。

Getting the time zone based on the locale may not be their actual time zone . 根据语言环境获取时区可能不是其实际时区

An example: Here in Australia, the locale is 'en-AU', but we have a few time zones with up to 3 hours difference. 例如:在澳大利亚,语言环境为“ en-AU”,但是我们有一些时区,相差最多3个小时。

I'd guess in the US they have this problem too. 我猜在美国他们也有这个问题。

A possible solution is to store UTC time instead. 一种可能的解决方案是存储UTC时间 If the user then adjusts his timezone in, say, his prefrences, or you use some other method of passing the time zone (client/browser info say via AJAX) then you can adjust the UTC time based on that using a java.util.Calendar instance. 如果用户随后调整了自己的时区(例如,他的偏好),或者您使用了其他传递时区的方法(客户端/浏览器信息通过AJAX进行了说明),则可以使用java.util.Calendar基于该时间调整UTC时间java.util.Calendar实例。

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

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