存储时间戳,其中UTC偏离字符串到Cassandra

时间:2016-11-25 16:24:56

标签: datetime cassandra timestamp utc

我想将带有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偏移量。谁能指出我怎么做?

1 个答案:

答案 0 :(得分:0)

通过使用 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()函数和格式化程序。