如何使用Java设置全局默认日期格式? [英] How can I set the global default date format in Java?

查看:836
本文介绍了如何使用Java设置全局默认日期格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我的背景:我从JDBC中读取日期值的异常,因为日期字符串不符合预期的格式。



(2011-07-22添加的文字):



似乎我需要精确的问题描述:我使用一个外部的专有数据库和一个专有的JDBC驱动程序。在数据库端无法知道甚至更改列类型。当我尝试通过ResultSet.getDate()或ResultSet.getObject()读取ResultSet列时,JDBC驱动程序中会触发一些异常,如1999年7月10日不是有效日期。我想要实现的是通过设置一些适当的全局默认日期格式来避免这种内部异常。也许我需要首先实现一些自定义的区域设置和全局Locale的安装?

解决方案

您可以设置默认的区域设置: / p>

  Locale.setDefault(Locale.US); 

或者,您可以使用其中一个 DateFormat 静态方法,它接受一个Locale来获取你感兴趣的Locale的格式。如果你的日期格式不符合一个标准的格式,你需要创建你自己的 SimpleDateFormat (基于模式),并确保您始终使用该模式,而不是默认模式。


Is there a way to set the default DateFormat class used for parsing strings into dates?

My background: I get exceptions reading date values from JDBC because the date string is not in the expected format.

(text added on 2011-07-22):

Seems I need to precise my question description: I use a foreign, proprietary database together with a proprietary JDBC driver. There is no possibility to know or even change the column type on database side. When I try to read the ResultSet columns via ResultSet.getDate() or ResultSet.getObject() some exception is triggered inside the JDBC driver like "10 Jul 1999 is not a valid date". What I want to achieve is to avoid this internal exception by setting some appropriate global default date format. Maybe I would need to implement some custom Locale first and the install that Locale globally?

解决方案

You can set your default Locale:

Locale.setDefault(Locale.US);

Alternatively, you can use one of the DateFormat static methods which accepts a Locale to just get the format for the Locale you're interested in. If your date format doesn't match one of the standard ones, you'll need to create your own SimpleDateFormat (based on a pattern) and make sure you always use that one instead of the default one.

这篇关于如何使用Java设置全局默认日期格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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