Java/MySQL 中没有时间或时区组件的日期 [英] Dates with no time or timezone component in Java/MySQL

查看:28
本文介绍了Java/MySQL 中没有时间或时区组件的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够存储没有时间组件的日期(年/月/日).它是日期的抽象概念,例如生日 - 我需要表示一年中的某个日期,而不是某个特定的时刻.

I need to be able to store a date (year/month/day) with no time component. It's an abstract concept of a date, such as a birthday - I need to represent a date in the year and not a particular instant in time.

我正在使用 Java 从一些输入文本中解析日期,并且需要存储在 MySQL 数据库中.无论数据库、应用程序或任何客户端处于哪个时区,它们都应该看到相同的年/月/日.

I am using Java to parse the date from some input text, and need to store in a MySQL database. No matter what timezone the database, application, or any client is in, they should all see the same year/month/day.

我的应用程序将在与数据库服务器具有不同系统时区的机器上运行,我无法控制它们.有没有人有一个优雅的解决方案来确保我正确存储日期?

My application will run on a machine with a different system timezone from the database server, and I don't have control over either. Does anyone have an elegant solution for ensuring I store the date correctly?

我能想到这些解决方案,但都不是很好:

I can think of these solutions, neither of which seems very nice:

  • 查询我的 MySQL 连接的时区并解析该时区中的输入日期
  • 将日期完全作为字符串 yyyy-MM-dd 处理

推荐答案

我得出的结论是,在我当前的应用程序(一个直接使用 jdbc 的简单实用程序)中,最好的方法是直接作为字符串插入.对于更大的 Hibernate 应用程序,我可能会费心编写自己的用户类型.不敢相信有人还没有在一些公开可用的代码中解决这个问题......

I concluded that the best way in my current application (a simple utility using jdbc directly) was to insert directly as a string. For a bigger Hibernate app I might bother to write my own user type. Can't believe someone hasn't already solved this problem in some publicly available code though...

这篇关于Java/MySQL 中没有时间或时区组件的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆