java - 使用Java读取CST时区的系统时间

标签 java

我正在尝试使用 Java 读取 CST 时区的系统日期。我尝试了下面的代码,但每当我使用 formatter.parse() 时,它都会返回 EST 时区的时间。

private Date getTodayInCST() {
    Calendar currentdate = Calendar.getInstance();
    DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    TimeZone obj = TimeZone.getTimeZone("CST");
    formatter.setTimeZone(obj);

    String today = formatter.format(currentdate.getTime());
    try {
        return formatter.parse(today);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return null;
}

最佳答案

tl;博士

ZonedDateTime.now( 
    ZoneId.of( "America/Chicago" )
)

详细信息

I am trying to read the system date in CST time zone

“CST”是指北美的中部标准时间,还是中国标准时间

指定proper time zone name格式为大洲/地区,如America/Montreal , Africa/Casablanca ,或太平洋/奥克兰。切勿使用 3-4 个字母的缩写,例如 ESTIST,因为它们不是真正的时区,不是标准化的,甚至不是唯一的上面显示的是 CST

ZoneId z = ZoneId.of( "America/Chicago" ) ; 

java.time

您正在使用麻烦的旧日期时间类,这些类现在已经成为遗留问题。被 java.time 类取代。

获取 UTC 的当前时刻。 Instant类代表UTC中时间线上的一个时刻。分辨率为nanoseconds (最多九 (9) 位小数)。

Instant instant = Instant.now() ;

2018-02-26T05:45:24.213610Z

调整到另一个时区。同一时刻,时间轴上的同一点,不同的挂钟时间。

ZonedDateTime zdt = instant.atZone( z ) ;

zdt.toString(): 2018-02-25T23:45:24.213610-06:00[America/Chicago]

以上字符串采用标准 ISO 8601 格式。 ZonedDateTime 类明智地扩展了该标准,将区域名称附加在方括号中。

如果要生成其他格式的 String 对象,请使用 DateTimeFormatter

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu HH:mm:ss" ) ;
String output = zdt.format( f ) ;
<小时/>

关于java.time

java.time框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧类 legacy日期时间类,例如 java.util.Date , Calendar , & SimpleDateFormat .

Joda-Time项目,现在位于 maintenance mode ,建议迁移到java.time类。

要了解更多信息,请参阅 Oracle Tutorial 。并在 Stack Overflow 上搜索许多示例和解释。规范为JSR 310 .

使用 JDBC driver符合JDBC 4.2或以后,您可以直接与数据库交换java.time对象。不需要字符串也不需要 java.sql.* 类。

从哪里获取java.time类?

ThreeTen-Extra项目通过附加类扩展了 java.time。该项目是 java.time future 可能添加的内容的试验场。您可能会在这里找到一些有用的类,例如 Interval , YearWeek , YearQuarter ,和more .

关于java - 使用Java读取CST时区的系统时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25767825/

相关文章:

java - 从 java 智能卡 APDU 收到奇怪的数据?

java - 我在我的盒子里部署 war 时遇到异常,它在另一个盒子里运行良好

java - 禁用的 JTable 上的手形光标

java - 多态性和基于实例的switch case

java - 未定义名为 'springSecurityFilterChain' 的 bean

java - 带有外部 Web 服务监控的 Spring Integration 应用程序

java - 使用 AES PKCS7Padding 加密和解密失败

java - Kotlin 将 PKCS1 转换为 PKCS8

java - File.lastModified 值会一直增加吗?

Java 格式化日期