I have string inputs as "03:00 PM" or "09:00 AM", which i want to convert it to formatted time or even to integer. So that I can compare them by the order of time. Anyone can help me with that?
Thank you in advance.
I have string inputs as "03:00 PM" or "09:00 AM", which i want to convert it to formatted time or even to integer. So that I can compare them by the order of time. Anyone can help me with that?
Thank you in advance.
Try this
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDateExample1 {
public static void main(String[] args)throws Exception {
String sDate1="03:00 PM";
Date date1=new SimpleDateFormat("HH:mm").parse(sDate1);
}
}
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
String input = "03:00 PM";
LocalTime time = LocalTime.parse(input, inputFormatter);
System.out.println(time);
This prints
15:00
Edit: Since your time format is in English, it may be considered cleaner to use this formatter instead:
DateTimeFormatter inputFormatter
= DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)
.withLocale(Locale.ENGLISH);
It nearly matches. The latter formatter formats hours before 10 with only one digit, e.g., 5:12 AM
, but also accepts two digits when parsing, so it works.
I recommend you use LocalTime
from java.time
for representing time of day, this is exactly what it is for. So it gives you good modelling and self-documenting code.
The other answers are correct but poor. While you should use library classes for your task, you should not use SimpleDateFormat
and Date
for at least three reasons. (1) They are long outdated and poorly designed; (2) DateFormat
and SimpleDateFormat
in particular are notoriously troublesome; (3) Date
does not represent a time-of-day.
LocalTime anotherTime = LocalTime.parse("09:00 AM", inputFormatter);
if (anotherTime.isBefore(time)) {
System.out.println("" + anotherTime + " comes before " + time);
} else {
System.out.println("" + time + " comes before " + anotherTime);
}
This prints
09:00 comes before 15:00
Again, use LocalTime
for comparison, it’s clearer than using formatted strings. Probably even better, LocalTime
implements Comparable
, so you can use Collections.sort()
and other functions that rely on a natural ordering of objects.
If you do want a formatted string, the first option is LocalTime.toString()
:
String formattedTime = time.toString();
System.out.println(formattedTime);
This prints the same output as we got above, 15:00
. If you want a different format, define a second DateTimeFormatter
and use it in LocalTime.format()
.
Yes, you can use java.time
on Android. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).You can use DateFormat. If you are sure that all is English, use Locale.ENGLISH
.
static Date convertTimeString(String timeString) {
try {
return DateFormat.getTimeInstance(DateFormat.SHORT, Locale.ENGLISH)
.parse(timeString);
} catch(ParseException e) {
Log.e("CONVERTDATE", "String \"" + timeString + "\" couldn't be parsed");
return null;
}
}
The best way to do that.
SimpleDateFormat myFormat = new SimpleDateFormat("hh:mm a");
String time="09:00 AM";
try {
Date date=myFormat.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
On the date variable you will have your time
This might not be a best solution. But what you can do is convert your input time to seconds and then compare integer values.
Below function can help you give an idea on getting seconds. (just a pseudo code. Not a tested one)
public int getSeconds(String timeValue){
String[] splitByColon = timeValue.split(":");
int hoursValue = Integer.parseInt(splitByColon[0]));
String[] splitForMins = splitByColon[1].split(" ");
if(splitForMins[1].equals("PM"))
{
hoursValue = hoursValue + 12;
}
int minutesValue = Integer.parseInt(splitForMins[0]);
return 3600*hoursValue + 60*minutesValue;
}
You can try the below code:
String strTime = "03:00 pm";
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm aa");
Date date = dateFormat.parse(strTime);
long time = date.getTime();
import java.util.*;
import java.text.*;
public class DateDemo {
public static void main(String args[]) {
String time1="10:00 AM",time2="11:00 PM";
DateFormat dfrmt = new SimpleDateFormat ("hh:mm a");
Date Dtime1 =new Date();
Date Dtime2 =new Date();
try{
Dtime1 = dfrmt.parse(time1);
Dtime2 = dfrmt.parse(time2);
}catch(Exception e){
}
if(Dtime1.compareTo(Dtime2)>0){
//DTime1 comes after Dtime2
System.out.println(dfrmt.format(Dtime1) + " > " + dfrmt.format(Dtime2));
}else if(Dtime1.compareTo(Dtime2)<0){
//Dtime1 Comes Before Dtime2
System.out.println(dfrmt.format(Dtime1) + " < " + dfrmt.format(Dtime2));
}
else{
//Equal
System.out.println(dfrmt.format(Dtime1) + " == " + dfrmt.format(Dtime2));
}
}
}
Try this to compare two dates;
Create datetime object and use comapreTo()
function