从BigQuery-java下载日期时将long转换为timestamp

从BigQuery-java下载日期时将long转换为timestamp,java,google-bigquery,Java,Google Bigquery,我正在从bigquery下载数据。 使用com.google.cloud.bigquery库 使用以下代码: String queryString = "SELECT * FROM `datasetId.tableId` where field=val;"; BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService(); // Create a query request QueryRe

我正在从bigquery下载数据。 使用com.google.cloud.bigquery库 使用以下代码:

    String queryString = "SELECT * FROM `datasetId.tableId` where field=val;";
    BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
    // Create a query request
    QueryRequest queryRequest =
            QueryRequest.newBuilder(queryString)
                    .setMaxWaitTime(60000L)
                    .setPageSize(1000L)
                    .setUseLegacySql(false)
                    .build();
    // Request query to be executed and wait for results
    QueryResponse queryResponse = bigquery.query(queryRequest);
    while (!queryResponse.jobCompleted()) {
        Thread.sleep(1000L);
        queryResponse = bigquery.getQueryResults(queryResponse.getJobId());
    }
    // Read rows
    Iterator<List<FieldValue>> rowIterator = queryResponse.getResult().iterateAll();
    while (rowIterator.hasNext()) {
        System.out.println(rowIterator.next());
    }
因此,我尝试使用以下代码进行转换:

private String convert(String value) {
    long lng = (long) Double.parseDouble(value);
    Date date = new Date(lng * 1000);
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    return dateFormat.format(date);
}
但我明白了:

 time ->"2017-01-18T10:28:55.000Z" date -> "2016-09-22T17:37:52.000Z"
一个日期相差2小时,另一个相差3小时


如何获取原始值?

问题在于时区。BigQuery以UTC格式存储其时间戳,因此您需要在格式化程序中指定UTC时区:

public static void main (String[] args){
   SimpleDateFormat dateFormatUTC = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
   dateFormatUTC.setTimeZone(TimeZone.getTimeZone("UTC"));

   System.out.println("time: " + dateFormatUTC.format(new Date(Double.valueOf("1.484728135674E9").longValue() * 1000)));
   System.out.println("date: " + dateFormatUTC.format(new Date(Double.valueOf("1.474555072424E9").longValue() * 1000)));
}
印刷品:

如果您使用的是Java 8,那么您可以使用Instant,它无论如何都是基于UTC的:

..
System.out.println("time: " + Instant.ofEpochMilli(Double.valueOf("1.484728135674E9").longValue() * 1000));
System.out.println("date: " + Instant.ofEpochMilli(Double.valueOf("1.474555072424E9").longValue() * 1000));
..
印刷品:

time: 2017-01-18T08:28:55.000Z
date: 2016-09-22T14:37:52.000Z
..
System.out.println("time: " + Instant.ofEpochMilli(Double.valueOf("1.484728135674E9").longValue() * 1000));
System.out.println("date: " + Instant.ofEpochMilli(Double.valueOf("1.474555072424E9").longValue() * 1000));
..
time: 2017-01-18T08:28:55Z
date: 2016-09-22T14:37:52Z