簡體   English   中英

我如何獲取日期時間戳為UTC

[英]how do i fetch date timestamp as UTC

我將日期時間戳存儲在DB中作為UTC值,同時檢索它我需要作為UTC時間,並需要轉換為特定的時區值。

即2015-05-01 00:09:30:00 UTC時間需要轉換為IST(或其他時區)

resultSet.getDate("VisitDate")

請幫忙。

Java 8

您可以將ZonedDateTime設置為UTC,然后使用類似的內容將其轉換為LocalDateTime

java.sql.Timestamp ts = resultSet.getTimestamp("VisitDate");
ZonedDateTime utcDateTime = ZonedDateTime.ofInstant(ts.toInstant(), ZoneId.of("UTC"));
LocalDateTime localDateTime = utcDateTime.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();

顯然,我在示例中使用了ZoneId.systemDefault() (將分區日期/時間轉換為本地日期/時間),但是您可以傳遞您想要/需要的區域

喬達時間

如果您不使用Java 8,那么與Joda-Time類似

java.sql.Timestamp ts = resultSet.getTimestamp("VisitDate");
LocalDateTime utcDateTime = new LocalDateTime(ts, DateTimeZone.UTC);
DateTime hereDateTime = utcDateTime.toDateTime(DateTimeZone.getDefault());
private final static String DATEFORMAT = "yyyy-MM-dd HH:mm:ss";
public static String getCurrentTimeInUTC(){

    final SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    final String utcTime = sdf.format(new Date());


    return utcTime;

}

U可以將UTC字符串更改為任何已知的時區字符串以獲得該格式。 如果這有用,請投票。 要更改時區,您可以使用此功能

public static String getLocalTime(String timeZone) throws ParseException{
     DateFormat formatter = null;
        Date convertedDate = null;

        DateFormat outputFormat=new  SimpleDateFormat(DATEFORMAT);
        formatter = new SimpleDateFormat(DATEFORMAT);
        formatter.setTimeZone(TimeZone.getTimeZone(timeZone));
        convertedDate = (Date) formatter.parse(getCurrentTimeInUTC());
        return outputFormat.format(convertedDate);
}

請享用 :-)

正如您所說的那樣,在設置為UTC時區的同時,但是當從DB重新檢索時區時,它不能再次為UTC,因為DB不會存儲時區信息以獲取更多詳細信息,請檢查此鏈接在DB中處理時區

因此,根據它可能會返回本地JVM或數據庫服務器時區設置的時區。

無論如何要更改時區,如其他答案所述,您可以使用SimpleDateFormat

  final SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
final String utcTime = sdf.format(new Date());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM