在Java中为不同时区生成报告

时间:2017-12-27 11:41:46

标签: java

作为我的要求的一部分,我必须发出一个SQL查询,该查询需要在昨天的午夜和今天的相应时区的午夜作为输入。是否有办法实现这一目标?

3 个答案:

答案 0 :(得分:1)

使用ZonedDateTime:

    String DATE_FORMAT = "dd-M-yyyy hh:mm:ss a";
    String dateInString = "22-1-2015 10:15:55 AM";
    LocalDateTime ldt = LocalDateTime.parse(dateInString, DateTimeFormatter.ofPattern(DATE_FORMAT));

    ZoneId singaporeZoneId = ZoneId.of("Asia/Singapore");
    System.out.println("TimeZone : " + singaporeZoneId);

    //LocalDateTime + ZoneId = ZonedDateTime
    ZonedDateTime asiaZonedDateTime = ldt.atZone(singaporeZoneId);
    System.out.println("Date (Singapore) : " + asiaZonedDateTime);

    ZoneId newYokZoneId = ZoneId.of("America/New_York");
    System.out.println("TimeZone : " + newYokZoneId);

    ZonedDateTime nyDateTime = asiaZonedDateTime.withZoneSameInstant(newYokZoneId);
    System.out.println("Date (New York) : " + nyDateTime);

    DateTimeFormatter format = DateTimeFormatter.ofPattern(DATE_FORMAT);
    System.out.println("\n---DateTimeFormatter---");
    System.out.println("Date (Singapore) : " + format.format(asiaZonedDateTime));
    System.out.println("Date (New York) : " + format.format(nyDateTime));

输出是:

TimeZone : Asia/Singapore
Date (Singapore) : 2015-01-22T10:15:55+08:00[Asia/Singapore]
TimeZone : America/New_York
Date (New York) : 2015-01-21T21:15:55-05:00[America/New_York]

---DateTimeFormatter---
Date (Singapore) : 22-1-2015 10:15:55 AM
Date (New York) : 21-1-2015 09:15:55 PM

使用此处的方法获取所需内容

示例摘自:Java – Convert date and time between timezone

答案 1 :(得分:0)

只需每小时运行一次你的cronjob,只生成当天结束时区的报告

答案 2 :(得分:0)

java.time

使用符合JDBC 4.2或更高版本的驱动程序,在Java 8或更高版本上运行,可以使用现代java.time类来取代麻烦的旧旧日期时间类。

确定“今天”和“昨天”意味着确定日期。确定日期需要时区。对于任何给定的时刻,日期在全球范围内因地区而异。

ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
LocalDate yesterday = today.minusDays( 1 ) ;

要查询数据库中的时间戳,我们需要特定的时刻。该问题规定午夜。 “午夜”一词含糊不清。让我们使用“一天中的第一时刻”。

永远不要假设这一天从00:00:00开始。夏令时(DST)等异常意味着它可能会在01:00:00等其他时间开始。让java.time确定一天的第一时刻。

ZonedDateTime start = yesterday.atStartOfDay( z ) ; 

通常,定义时间跨度的最佳方法是半开方法,其中开头是包含,而结尾是独占。因此,我们希望从一天的第一时刻开始,然后运行,但不包括 next 日的第一个时刻。

ZonedDateTime stop = today.atStartOfDay( z ) ; 

在半开放状态下,我们使用SQL命令BETWEEN

SQL

SELECT * FROM t 
WHERE event >= ? AND event < ? ;

爪哇

myPreparedStatement.setObject( 1 , start ) ;
myPreparedStatement.setObject( 2 , stop ) ;

要检索时间戳,请使用getObject

Instant instant = myResultSet.getObject( "event" , Instant.class ) ;

要从UTC移至区域,请应用ZoneId

ZonedDateTime zdt = instant.atZone( z ) ;
相关问题