【问题标题】:Store timestamp with UTC offset from string into Cassandra将带有 UTC 偏移量的时间戳从字符串存储到 Cassandra
【发布时间】:2017-04-10 02:23:42
【问题描述】:

我想将带有 UTC 偏移量的时间戳数据从字符串存储到 Cassandra 时间戳列中。我的字符串类似于yyyy-MM-dd HH:mm:ssZ,其中Z 是类似于+0100 的字符串。我想要的只是将它作为时间戳存储在 event_time 列中,包括我的 UTC 偏移量。使用 DataStax Java 驱动程序:

PreparedStatement statement = session.prepare(
            "INSERT INTO " + table + "( " + frame + ", device_uuid, event_time, value)"
                    + "VALUES (?,?,?,?);");
            BoundStatement boundStatement = new BoundStatement(statement);
            session.execute(boundStatement.bind(frame_val, uuid, date, value));

date 是这样计算的:

String str = "2016-11-22 02:33:25+0100";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
    Date date = null;
    try {
        date = formatter.parse(str);
    } catch (ParseException e) {
        System.out.println("Error in parsing date");
        e.printStackTrace();
    }
    return date;

问题是,我总是得到像2016-11-25 13:24:07+0000 这样的值,所以偏移量总是设置为零;我在这里检查了数据格式https://docs.datastax.com/en/cql/3.1/cql/cql_reference/timestamp_type_r.html,但我不明白我哪里出错了。我认为问题在于我不希望 Cassandra 使用它的时区,但我想在时间戳值中“注入”我的 UTC 偏移量。有人能指点我怎么做吗?

【问题讨论】:

  • 您的 event_time 已正确存储在 Cassandra 中。它只是显示格林威治标准时间。
  • 嗨,你能解决这个问题吗?你能让cassandra也存储偏移量吗?请问我有同样的问题。谢谢

标签: datetime cassandra timestamp utc


【解决方案1】:

通过使用 Joda Time 包,您可以轻松实现这一目标。

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public Class Util {
static DateTimeFormatter formatter;

    public static DateTime strToDateTime(String s, String format) {
        DateTime retValue = null;
        formatter = DateTimeFormat.forPattern(format);
        try {
            retValue = formatter.withOffsetParsed().parseDateTime(s);
        } catch (Exception e) {
            return retValue;
        }
        return retValue;
    }
}


@Test
public void strToDateTime() throws Exception {
    DateTime s = Util.strToDateTime("2016-11-22 02:33:25+0100", "yyyy-MM-dd HH:mm:ssZ");
    System.out.println(s);
}

在尝试解析 dateTime 字符串值之前,将 withOffsetParsed() 函数与格式化程序一起使用。

【讨论】:

    猜你喜欢
    • 2022-06-27
    • 1970-01-01
    • 2017-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多