Java/Servlet:获取当前 sql.Date
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/829358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java/Servlet: get current sql.Date
提问by Artemij
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?
有什么建议?有没有更有效的方法来做到这一点?
回答by Paul Tomblin
If you want the time, you need a java.sql.Timestamp not a java.sql.Date, and a timestamp column in the database.
如果你想要时间,你需要一个 java.sql.Timestamp 而不是 java.sql.Date,以及数据库中的时间戳列。
回答by kgiannakakis
Note that request.getLocaleuses the value of Accept-Language heading and may not always give you the correct locale.
请注意request.getLocale使用 Accept-Language 标题的值,并且可能并不总是为您提供正确的语言环境。
回答by Clinton
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 timeinstead. 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.
一个可能的解决方案是存储 UTC 时间。如果用户然后调整他的时区,例如,他的偏好,或者您使用其他一些传递时区的方法(客户端/浏览器信息通过 AJAX 说),那么您可以根据使用java.util.Calendar
实例来调整 UTC 时间。
回答by Aniruddh
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());
回答by Hugh
Even a more compact solution ;)
甚至更紧凑的解决方案;)
java.sql.Date timeNow = new Date(Calendar.getInstance().getTimeInMillis());