java 如何将日期时间字符串转换为整数数据类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15307171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert a datetime string into an integer datatype?
提问by maddy
String timerStop1 = String.format("%02d", hours) + ":"+String.format("%02d", minutes) + ":"
+ String.format("%02d", seconds);
I'm taking the above concatenated string value and I want to convert it into an integerto use in my android application. How do I do this?
我正在使用上面连接的字符串值,我想将它转换为一个整数以在我的 android 应用程序中使用。我该怎么做呢?
回答by jrd1
A first step will be to convert the time in HH:MM:SSformat (which is how your string is formatted) to that of seconds as per the following:
第一步是将HH:MM:SS格式的时间(这是您的字符串的格式)转换为秒数,如下所示:
String timerStop1 = String.format("%02d", hours) + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", seconds);
String[] timef=timerStop1.split(":");
int hour=Integer.parseInt(timef[0]);
int minute=Integer.parseInt(timef[1]);
int second=Integer.parseInt(timef[2]);
int temp;
temp = second + (60 * minute) + (3600 * hour);
System.out.println("seconds " + temp);
However, this only gets the time as seconds (integers), but not as a timestamp!
但是,这只能以秒(整数)的形式获取时间,而不是时间戳!
UPDATE:
更新:
And, as Colin pointed out, given that you already have access to the variables: hours, minutes, seconds - why not do it like what he suggested - which is completely correct?
而且,正如 Colin 指出的那样,鉴于您已经可以访问变量:小时、分钟、秒——为什么不按照他的建议去做——这是完全正确的?
https://stackoverflow.com/a/15307211/866930
https://stackoverflow.com/a/15307211/866930
That's because the OP wants to know how to convert an HH:MM:SS string to an integer - if so, then this is the most general way in which to do so, IMO.
那是因为 OP 想知道如何将 HH:MM:SS 字符串转换为整数 - 如果是这样,那么这是最通用的方法,IMO。
回答by Visruth
It is not possible to parse timerStop1
to integer because timerStop1
contains characters other than numbers.
无法解析timerStop1
为整数,因为timerStop1
包含数字以外的字符。
回答by Breavyn
Can you just use the variables hours, minutes, seconds. Assuming that by converting to an integer you want the total number of seconds.
你能不能只使用变量小时、分钟、秒。假设通过转换为整数,您需要总秒数。
int time = seconds + (minutes * 60) + (hours * 3600);
回答by Festus Tamakloe
the tostring()
method hier not necessary
tostring()
不需要的方法
Integer.parseInt(timerStop1);