Reputation: 1219
My app is very simple, it consist of a string variable which consists of both date and time in it, from that string i need to fetch only time and convert it into milliseconds, so that i can pass that milliseconds to alarm manager to trigger alarm.
Here is the code of my MainActivity looks like:
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();
}
when i'm printing calendar.getTime i'm getting both date and time i.e; Tue Mar 14 15:26:45 GMT+05:30 2017, instead of that i need to get 15:26:45 value and convert that value into milli seconds.
Upvotes: 0
Views: 4444
Reputation: 560
Try below code:
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();
}
Upvotes: 0
Reputation: 6426
Try to use this:
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();
}
Upvotes: 1
Reputation: 2405
Try this
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());
Upvotes: 0
Reputation: 3527
You can easily use calendar.getTimeInMillis()
to get milliseconds.
Upvotes: 0