将UTC时间偏移量与字符串的UTC偏移量存储到卡桑德拉
问题描述:
我想将时间戳数据与字符串的UTC偏移量存储到卡桑德拉时间戳列中。我的字符串类似于yyyy-MM-dd HH:mm:ssZ
,其中Z是类似+0100
的字符串。我只需要将其作为时间戳存储在event_time
列中,包括我的UTC偏移量。使用DataStax Java驱动程序:将UTC时间偏移量与字符串的UTC偏移量存储到卡桑德拉
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
的计算是这样的:有偏移总是被设置为零像2016-11-25 13:24:07+0000
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;
的问题是,我总是得到的值,所以,我在这里检查了数据格式https://docs.datastax.com/en/cql/3.1/cql/cql_reference/timestamp_type_r.html,我不明白我哪里出错了。我认为问题在于我不希望Cassandra使用它的时区,但我想在时间戳值中“注入”我的UTC偏移量。任何人都可以指出我该怎么做?
答
通过使用约达时间包,你可以很容易地做到这一点。
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);
}
试图解析日期时间字符串值之前使用withOffsetParsed()功能与格式。
您的event_time正确存储在Cassandra中。 这只是在GMT显示时间。 –
http://stackoverflow.com/questions/32778433/cassandra-cqlsh-not-displaying-correct-timezone –