我的应用程序非常简单,它由一个字符串变量组成,其中包含日期和时间,从该字符串我只需要获取时间并将其转换为毫秒,以便我可以将该毫秒传递给警报管理器触发警报。
以下是我的MainActivity的代码:
try {
String string = "Mon, 10 Mar 2017 03:26:00 p.m.";
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(string.substring(17, 19)));
calendar.set(Calendar.MINUTE, Integer.parseInt(string.substring(20, 22)));
calendar.set(Calendar.AM_PM, string.contains("a.m.") ? 0 : 1);
Toast.makeText(getApplicationContext(), "cal: " + calendar.getTime()+ " , milli sec: "+calendar.getTimeInMillis(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "exe: " + e, Toast.LENGTH_LONG).show();
}
当我打印 calendar.getTime 时,我同时获得日期和时间,即; Tue Mar 14 15:26:45 GMT + 2017年5月30日,而不是我需要获得 15:26:45 值并将该值转换为毫秒。
答案 0 :(得分:1)
尝试使用它:
try {
String string = "Mon, 10 Mar 2017 03:26:00 p.m.";
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, Integer.parseInt(string.substring(17, 19)));
calendar.set(Calendar.MINUTE, Integer.parseInt(string.substring(20, 22)));
calendar.set(Calendar.AM_PM, string.contains("a.m.") ? 0 : 1);
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Toast.makeText(getApplicationContext(), "cal: " + dateFormat.format(calendar.getTime())+ " , milli sec: "+calendar.getTimeInMillis(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "exe: " + e, Toast.LENGTH_LONG).show();
}
答案 1 :(得分:0)
您可以轻松使用calendar.getTimeInMillis()
来获取毫秒数。
答案 2 :(得分:0)
试试这个
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String inputString = "00:01:30.500";
Date date = sdf.parse("1970-01-01 " + inputString);
System.out.println("in milliseconds: " + date.getTime());
答案 3 :(得分:0)
请尝试以下代码:
try {
String string = "Mon, 10 Mar 2017 03:26:00 p.m.";
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(string.substring(17, 19)));
calendar.set(Calendar.MINUTE, Integer.parseInt(string.substring(20, 22)));
calendar.set(Calendar.AM_PM, string.contains("a.m.") ? 0 : 1);
calendar.getTimeInMillis();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String time = sdf.format(new Date(calendar.getTimeInMillis()));
long timeinmili=0;
try {
Date date1 = sdf.parse(time);
timeinmili = date1.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("Time in Mili Seconds :"+timeinmili );
} catch (Exception e) {
e.printStackTrace();
}