如何在android中将字符串转换为时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23868290/
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 to convert string to time in android?
提问by Jigar Shekh
I am getting string from voice(Speech to text). When i speak time it's display e.g. "530pm". I want to convert only time from string. e.g. "530pm"to 05:30 PM. How can i achieve this? Thanks in advance.
我正在从语音(语音到文本)中获取字符串。当我说话时,它会显示例如“530pm”。我只想从字符串转换时间。例如“530pm”到05:30 PM。我怎样才能做到这一点?提前致谢。
I try this code but not work
我尝试使用此代码但不起作用
String s= "530 pm";
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm aa");
try {
Date date1 = dateFormat.parse(s);
Log.e("Time", ""+date1);
} catch (ParseException e) {
// TODO Auto-generated catch block
Log.e("Error", ""+e);
}
回答by Dario
Read SimpleDateFormat documentation (parse&format methods and pattern syntax).
阅读 SimpleDateFormat 文档(解析和格式化方法和模式语法)。
http://developer.android.com/reference/java/text/SimpleDateFormat.html
http://developer.android.com/reference/java/text/SimpleDateFormat.html
String time = "530pm";
SimpleDateFormat dateFormat = new SimpleDateFormat("hmmaa");
SimpleDateFormat dateFormat2 = new SimpleDateFormat("hh:mm aa");
try {
Date date = dateFormat.parse(time);
String out = dateFormat2.format(date);
Log.e("Time", out);
} catch (ParseException e) {
}
回答by user3668424
final String NEW_FORMAT = " hh:mm";
final String OLD_FORMAT = "hh:mm:ss";
String formatDate;
SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
Date d = null;
try {
d = sdf.parse(Value);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sdf.applyPattern(NEW_FORMAT);
formatDate=sdf.format(d);