简体   繁体   English

Java将字符串yyyy-MM-dd HH:mm:ss转换为加拿大/东部时区的时间戳

[英]Java Convert String yyyy-MM-dd HH:mm:ss to timestamp of Canada/Eastern timezone

I have to get DateTime with using TimeZone and then get Timestamp from that DateTime 我必须使用TimeZone获取DateTime,然后从该DateTime获取时间戳

My Code is give below : 我的代码如下:

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dt = new Date();
String currentTime = formatter.format(dt);
System.out.println("currentTime>>>>" + currentTime);

DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("Canada/Eastern"));
Date parsedDate = format.parse(currentTime);
System.out.println("parsedDate>>>>" + parsedDate);
Timestamp timestamp = new Timestamp(parsedDate.getTime());
System.out.println("timestamp>>>>>>" + timestamp);

Problem is that I am not getting right datetime of Canada/Eastern TimeZone in timestamp. 问题是我在时间戳中没有得到正确的加拿大/东部时区的日期时间。

I am getting the below time 我正在下面的时间

currentTime>>>>2016-11-09 15:17:09
parsedDate>>>>Thu Nov 10 01:47:09 IST 2016
timestamp>>>>>>2016-11-10 01:47:09.0

Indian time is correct : 2016-11-09 15:17:09
When I parse it to Canada/Eastern it shows : Thu Nov 10 01:47:09 IST 2016

But eastern canada time is 04:50:21 EST Wednesday, 9 November 2016 但是加拿大东部时间是04:50:21 EST Wednesday, 9 November 2016东部时间04:50:21 EST Wednesday, 9 November 2016

I am using Java with Eclipse Mars 1. 我将Java与Eclipse Mars 1结合使用。

Timestamp is unique and same every where in all timezones, which is value of new Date() in millis. 时间戳是唯一的,并且在所有时区中的每个地方都相同,这是新的Date()的值,以毫秒为单位。 What you are looking for here is formatted time of given timestamp (dt in above example.). 您在这里寻找的是给定时间戳的格式化时间(上例中的dt)。

Date dt = new Date();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

System.out.println("IST time: " + format.format(dt));

format.setTimeZone(TimeZone.getTimeZone("Canada/Eastern"));

String parsedDate = format.format(dt);

System.out.println("Canada Time: " + parsedDate);

Output: IST time: 2016-11-09 16:33:22 Canada Time: 2016-11-09 06:03:22 输出:IST时间:2016-11-09 16:33:22加拿大时间:2016-11-09 06:03:22

tl;dr TL;博士

Instant.now()
       .atZone( ZoneId.of( "America/Toronto" ) )

No parsing! 没有解析! Do not parse to adjust time zone. 解析调整时区。

Avoid the troublesome old classes: java.text.SimpleDateFormat , java.util.Date , java.util.TimeZone . 避免麻烦的旧类: java.text.SimpleDateFormatjava.util.Datejava.util.TimeZone

java.time java.time

You are using troublesome old date-time classes, now legacy, supplanted by the java.time classes. 您正在使用麻烦的旧日期时间类(现在已遗留),由java.time类取代。

Instant

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction). Instant类以UTC表示时间轴上的时刻,分辨率为纳秒 (最多十进制的九(9)位数字)。

Instant instant = Instant.now();

2016-11-10T04:52:02.586Z 2016-11-10T04:52:02.586Z

Time zone 时区

You can adjust this Instant into a time zone by applying a ZoneId to get a ZonedDateTime . 您可以调整该Instant通过施加到一个时区ZoneId获得ZonedDateTime

Do not parse as a way to adjust time zone! 解析,以此来调整时区! perhaps you are conflating a date-time object with a string that might represent its value. 也许您正在将日期时间对象与可能表示其值的字符串进行混合。 A date-time object can generate a string, and can parse a string, but the string is always distinct and separate from the date-time object. 日期时间对象可以生成一个字符串,并且可以解析一个字符串,但是该字符串始终与日期时间对象是不同的且分开的。

Specify a proper time zone name in the format of continent/region , such as America/Montreal , Africa/Casablanca , or Pacific/Auckland . continent/region的格式指定正确的时区名称 ,例如America/MontrealAfrica/CasablancaPacific/Auckland Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!). 切勿使用ESTIST等3-4个字母的缩写,因为它们不是真实的时区,不是标准化的,甚至不是唯一的(!)。

Furthermore, your Canada/Eastern zone is actually just an alias for the real zone of America/Toronto . 此外,您的Canada/Eastern区域实际上只是America/Toronto的真实区域的别名。

ZoneId z = ZoneId.of( "America/Toronto" );
ZonedDateTime zdt = instant.atZone( z );

2016-11-09T23:52:02.586-05:00[America/Toronto] 2016-11-09T23:52:02.586-05:00 [美国/多伦多]

You could adjust into India time as well. 您也可以调整到印度时间。

ZoneId zKolkata = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdtKolkata = instant.atZone( zKolkata );

2016-11-10T10:22:02.586+05:30[Asia/Kolkata] 2016-11-10T10:22:02.586 + 05:30 [亚/加尔各答]

Dump to console. 转储到控制台。

System.out.println( "instant: " + instant );
System.out.println( "zdt: " + zdt );
System.out.println( "zdtKolkata: " + zdtKolkata );

instant: 2016-11-10T04:52:02.586Z 即时:2016-11-10T04:52:02.586Z

zdt: 2016-11-09T23:52:02.586-05:00[America/Toronto] zdt:2016-11-09T23:52:02.586-05:00 [美国/多伦多]

zdtKolkata: 2016-11-10T10:22:02.586+05:30[Asia/Kolkata] zdtKolkata:2016-11-10T10:22:02.586 + 05:30 [亚洲/加尔各答]

See live code in IdeOne.com . 请参阅IdeOne.com中的实时代码

Database 数据库

By Timestamp I assume you meant java.sql.Timestamp . 通过Timestamp我假设您的意思是java.sql.Timestamp That class is now outmoded by the java.time classes, if you have a JDBC driver that complies with JDBC 4.2 or later. 如果您具有符合JDBC 4.2或更高版本的JDBC驱动程序,则该类现在已被java.time类淘汰。 Just pass the Instant object to PreparedStatement::setObject . 只需将Instant对象传递给PreparedStatement::setObject Fetch via ResultSet::getObject . 通过ResultSet::getObject获取。

myPreparedStatement.setObject( … , instant );

If your JDBC driver does not comply, fall back to converting to java.sql.Timestamp . 如果您的JDBC驱动程序不符合要求,请退回转换为java.sql.Timestamp But minimize use of that class, only for talking to the database. 但是,仅在与数据库对话时,尽量减少使用该类。 Immediately convert back into java.time. 立即转换回java.time。 Do not attempt business logic with Timestamp . 不要尝试使用Timestamp业务逻辑。

java.sql.Timestamp ts = java.sql.Timestamp.from( instant );

About java.time 关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat . 这些类取代了麻烦的旧的旧式日期时间类,例如java.util.DateCalendarSimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to java.time. 现在处于维护模式Joda-Time项目建议迁移到java.time。

To learn more, see the Oracle Tutorial . 要了解更多信息,请参见Oracle教程 And search Stack Overflow for many examples and explanations. 并在Stack Overflow中搜索许多示例和说明。 Specification is JSR 310 . 规格为JSR 310

Where to obtain the java.time classes? 在哪里获取java.time类?

  • Java SE 8 and SE 9 and later Java SE 8SE 9及更高版本
    • Built-in. 内置。
    • Part of the standard Java API with a bundled implementation. 标准Java API的一部分,具有捆绑的实现。
    • Java 9 adds some minor features and fixes. Java 9添加了一些次要功能和修复。
  • Java SE 6 and SE 7 Java SE 6SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport . java.time的许多功能在ThreeTen- Backport中都被反向移植到Java 6和7。
  • Android Android的

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time. 该项目为将来可能在java.time中添加内容提供了一个试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more . 您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多

You can set the TimeZone based on GMT. 您可以基于格林尼治标准时间设置时区。 We know that Canada time is GMT-5 , so you can get the current Canada time like this: 我们知道加拿大时间是GMT-5 ,因此您可以这样获取当前加拿大时间:

    TimeZone tz = TimeZone.getTimeZone("GMT-5");
    Calendar c = Calendar.getInstance(tz);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CANADA);

    dateFormat.setTimeZone(tz);

    System.out.println(dateFormat.format(c.getTime()));

Output: 2016-11-09 06:08:47 输出:2016-11-09 06:08:47

You need to explicitly use DateFormat.setTimeZone() to print the Date in the desired timezone. 您需要显式使用DateFormat.setTimeZone()在所需的时区中打印日期。 If you don't do this, the c.getTime() result will be your zone current time. 如果不这样做,则c.getTime()结果将是您区域的当前时间。

A Timestamp doesn't have a time zone in Java, it only represents a moment in time based on a number of milliseconds elapsed since a reference point, the epoch. Timestamp在Java中没有时区,它仅表示自参考点(纪元)以来经过的毫秒数的时刻。

So it seems to me that you want your Timestamp to point to the current instant, which would be written very simply: 因此在我看来,您希望您的时间戳指向当前时刻,该时刻的编写非常简单:

//with Java 8
Timestamp ts = Timestamp.from(Instant.now());

//or prior to Java 8:
Timestamp ts = new Timestamp(new Date().getTime());

暂无
暂无

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

相关问题 将java.sql.timestamp从yyyy-MM-dd hh:mm:ss转换为MM-dd-yyyy hh:mm:ss - Convert java.sql.timestamp from yyyy-MM-dd hh:mm:ss to MM-dd-yyyy hh:mm:ss 如何在Java中将“ YYYY-MM-DD hh:mm:ss”转换为UNIX时间戳? - How to convert “YYYY-MM-DD hh:mm:ss” to UNIX timestamp in Java? 在 Java 中将日期格式“EEE MMM dd HH:mm:ss zzzz yyyy”转换为“yyyy-MM-dd'T'HH:mm:ss” - Convert date fomat “EEE MMM dd HH:mm:ss zzzz yyyy” to “yyyy-MM-dd'T'HH:mm:ss” in Java 如何验证时间戳记(yyyy-MM-dd HH:mm:ss)和(yyyy-MM-dd) - how to validate the timestamp (yyyy-MM-dd HH:mm:ss) and (yyyy-MM-dd) 将EEE MMM dd HH:mm:ss ZZZ yyyy转换为YYYY-MM-dd JAVA - Convert EEE MMM dd HH:mm:ss ZZZ yyyy to YYYY-MM-dd JAVA 将 YYYY-MM-DD'T'HH:MM:SS:SSS+HHMM 格式的输入日期转换为 java.sql.Timestamp 与来自输入的时区 - Convert input date in YYYY-MM-DD'T'HH:MM:SS:SSS+HHMM format to the java.sql.Timestamp with the timezone from input 将MYSQL日期时间值转换为UTC时区格式yyyy-MM-dd'T'HH:mm:ss'Z' - convert MYSQL datetime value to UTC Timezone format yyyy-MM-dd'T'HH:mm:ss'Z' 如何使用 Java 将 yyyy-mm-dd hh:mm:ss.ms 转换为 mm/dd/yyyy hh24:mi - How to convert yyyy-mm-dd hh:mm:ss.ms to mm/dd/yyyy hh24:mi using Java 如何将 java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) 格式化为日期(yyyy-MM-dd HH:mm:ss) - How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss) Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") 将时区作为 IST - Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM