我想知道如何在Java中创建一个表达式,该表达式接受格式为"1999-12-30 12:34:45“的日期变量,并将其转换为Int holding "19991230”。
这可能是其他人会喜欢的,特别是人们提取和清理数据以加载到数据仓库中。
我的猜测是,需要更改日期模式,转换为字符串,截断第一部分(8个字符),并转换为整数。
想法?
(更新)我在解释这个问题上的错误。生成的int将作为日期维度的key/Fk id提供服务。应该执行类似的操作来创建Time-of-Day维度的键。int将减少事实表中消耗的大小,这些int键将存储在事实表中。查看相关答案:https://stackoverflow.com/a/8416548/1132571
发布于 2012-01-06 00:24:49
使用SimpleDateFormat类很容易做到这一点。但是,正如其他人所提到的,您可能应该将纪元时间戳存储为数据库timestamp列,而不是以int形式存储日期。当您稍后使用SQL操作数据时,它会导致问题。
public static void main(String[] args) throws ParseException {
String dateStr = "1999-12-30 12:34:45";
String formatStr = "yyyy-MM-dd HH:mm:ss";
String formatStrOther = "yyyyMMdd";
Date testDate = null;
SimpleDateFormat sdf= new SimpleDateFormat(formatStr);
SimpleDateFormat sdfOther= new SimpleDateFormat(formatStrOther);
sdf.setLenient(false);
testDate = sdf.parse(dateStr);
Integer otherDate = Integer.valueOf(sdfOther.format(testDate));
System.out.println("Newly formatted date in int is: " + otherDate); //prints Newly formatted date in int is: 19991230
}发布于 2012-01-06 00:21:53
只需删除特殊字符,然后转换为int
Integer.parseInt("1999-12-30 12:34:45".replaceAll("[- :]", ""));
在您的例子中,您只需要日期,而不是时间,因此它将是:
Integer.parseInt("1999-12-30 12:34:45".substring(0,10).replaceAll("-", ""));
我应该提一下,只有在原始格式正确的情况下,这才能起作用。而且它实际上相当难看,我宁愿使用long和getTime -也许还有simpleDateFormat。您真的不想丢弃有用的数据!
发布于 2012-01-06 00:18:18
getTime会用这个信息给你一个长整型,整数就不够大了。
http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Date.html#getTime()
https://stackoverflow.com/questions/8745807
复制相似问题