I wrote the following code to get the time
public String getTime() {
final Calendar cld = Calendar.getInstance();
String time = cld.get(Calendar.HOUR) + ":" + (cld.get(Calendar.MINUTE));
try {
Date date = new SimpleDateFormat("HH:mm").parse(time);
time = new SimpleDateFormat("HH:mm").format(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return time;
}
This always give me time like
11:59
01:07
But I need in 24 hrs format like:
11:59
13:07
How to change the code.
Use HOUR_OF_DAY instead of HOUR.
Use Calendar.HOUR_OF_DAY instead.
Calendar.HOUR = Field number for get and set indicating the hour of the morning or afternoon. HOUR is used for the 12-hour clock. E.g., at 10:04:15.250 PM the HOUR is 10.
Calendar.HOUR_OF_DAY = Field number for get and set indicating the hour of the day. HOUR_OF_DAY is used for the 24-hour clock. E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22.
Here's the code:
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
String time = hour + ":" + minute;
HH:mm is correct. 01:07 is 1am and 13:07 is 1pm. Wait until 1pm and see or create a date object and test it.
Related
I needed to convert only the hour part of 12 hour time string to 24 hour format. I'm not interested in other than hour parts of a date string. SimpleDateFormatter is notoriously buggy and I in fact I'm more interested in the conversion algorithm itself. So what I want is to find the algorithm to convert the hour part. This is example of an uncleaned string containing hour part: "12:15PM". Sometimes there is spaces between minutes and meridiem sometimes not. Sometimes it has also character 160. So before conversion method I check and clean the string parts and then feed then meridiem(am or pm) and hour to the method which returns hour as 24 hour format int.
This is my naive style code for beginners to convert an hour in 12 hour format to an hour in 24 format.
public static int convert12to24(String meridiem, String hour) {
//meridiem is that am or pm,
meridiem = meridiem.toLowerCase();
int h_12 = 0;
int h_24 = 0;
try {
h_12 = Integer.parseInt(hour);
} catch (NumberFormatException e) {
e.printStackTrace();
}
if (h_12 == 12) {
//this is the midnight hour
if (meridiem.contains("am")) {//generally before noon
h_24 = 0;
} else {//this is the hour starting at noon
h_24 = 12;
}
} else if (h_12 >= 1)//all the rest
{
if (meridiem.contains("am")) {
//hour starting after first hour at midnight to 11 facing noon
h_24 = h_12;
} else {//pm hours starting right after first hour after noon
h_24 = h_12 + 12;
}
}
return h_24;
}
java.time
I recommend using java.time, the modern Java date and time API, rather than your own calendar implementation. It can be used in all locales.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:mma", Locale.ENGLISH);
String timeString12Hours = "12:15PM";
LocalTime time = LocalTime.parse(timeString12Hours, formatter);
System.out.println("Time: " + time);
int hour = time.getHour();
System.out.println("Hour of day in 24 hour format: " + hour);
Output is:
Time: 12:15
Hour of day in 24 hour format: 12
What we get for free from java.time is validation. This code will detect if meridiem is not either AM or PM, or the hour is outside the range 1 through 12 or not a number at all.
Under no circumstances use the SimpleDateFormat class mentioned in the question. It’s a notorious troublemaker of a class and long outdated.
Edit: If for compatibility with old code that I don’t know and that you haven’t got time to clean up at the moment you need the method signature from your own answer:
private static DateTimeFormatter meridiemHourFormatter
= DateTimeFormatter.ofPattern("ahh", Locale.ENGLISH);
public static int convert12to24(String meridiem, String hour) {
String meridiemHour = meridiem + hour;
return LocalTime.parse(meridiemHour, meridiemHourFormatter).getHour();
}
Trying it out:
System.out.println(convert12to24("PM", "12"));
12
Every reader can decide for himself or herself: Which method implementation takes less energy to understand if in a hurry, yours or mine?
Link: Oracle tutorial: Date Time explaining how to use java.time.
I want to check if my Date value from -
Date d = convertCurrentTimeToSpecificTimeZone("America/Chicago", 2, 30);
falls in the range of 10am to 6 pm.
I found some similar links on StackOverflow similar question and used some of the code from this thread.
All I want to check if the current time from any timezone falls under the range of 10 am to 6 pm. If Yes, print "yes" else print "no".
Currently for below code:
String string1 = "10:11:13";
Date time1 = new SimpleDateFormat("HH:mm:ss").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
calendar1.add(Calendar.DATE, 1);
System.out.println(calendar1.getTime().toString());
It just prints the 10:11 am time of 1970 year. Like this - Fri Jan 02 10:11:13 IST 1970.
But I want to check if today's or any future date time falls in the range of 10 am to 6pm.
Below is the code reference:
public static Date convertCurrentTimeToSpecificTimeZone(String timeZone, int increaseDateBy,
int increaseMinutesBy) {
Calendar calendar = Calendar.getInstance();
TimeZone fromTimeZone = calendar.getTimeZone();
TimeZone toTimeZone = TimeZone.getTimeZone(timeZone);
calendar.setTimeZone(fromTimeZone);
calendar.add(Calendar.MILLISECOND, fromTimeZone.getRawOffset() * -1);
if (fromTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
}
calendar.add(Calendar.MILLISECOND, toTimeZone.getRawOffset());
if (toTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, toTimeZone.getDSTSavings());
}
increaseCalenderDateBy(calendar, increaseDateBy);
increaseCalenderMinuteBy(calendar, increaseMinutesBy);
return calendar.getTime();
}
public static void getTimeBetweenRange() throws ParseException {
String string1 = "10:11:13";
Date time1 = new SimpleDateFormat("HH:mm:ss").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
calendar1.add(Calendar.DATE, 1);
System.out.println(calendar1.getTime().toString());
String string2 = "18:49:00";
Date time2 = new SimpleDateFormat("HH:mm:ss").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
System.out.println(calendar2.getTime().toString());
Date d = convertCurrentTimeToSpecificTimeZone("America/Chicago", 2, 30);
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(d);
System.out.println(calendar3.getTime().toString());
Date x = calendar3.getTime();
if (x.after(calendar1.getTime()) && x.before(calendar2.getTime())) {
// checkes whether the current time is between 14:49:00 and 20:11:13.
System.out.println(true);
} else
System.out.println(false);
}
So the output for my below code is:
Fri Jan 02 10:11:13 IST 1970
Fri Jan 02 18:49:00 IST 1970
Fri Jan 31 03:15:07 IST 2020
It’s not very clear. For this answer I am assuming that all of your times are to be understood in America/Chicago time zone. Please revert if this was not what you intended.
java.time
ZoneId zone = ZoneId.of("America/Chicago");
ZonedDateTime zdt = ZonedDateTime.now(zone).plusDays(2).plusMinutes(30);
LocalTime rangeStart = LocalTime.parse("10:11:13");
LocalTime rangeEnd = LocalTime.parse("18:49:00");
LocalTime time = zdt.toLocalTime();
if (!time.isBefore(rangeStart) && time.isBefore(rangeEnd)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
When I ran this code snippet just now (at 11:30 Chicago time), the output was:
Yes
I am using java.time, the modern Java date and time API, and recommend that you do the same. It’s so much nicer to work with than the old, outdated and poorly designed classes Date, SimpleDateFormat, Calendar and TimeZone.
A LocalTime is a time of day from 00:00 (inclusive) to 24:00 (exclusive). By comparing LocalTimeobjects we are ignoring the date and have no trouble with irrelevant dates in 1970 or some other time in history.
Edit:
Also is it possible to get the date and time of rangeStart and
rangeEnd in order to verify for which particular day and time we are
checking the conditions?
No, that would not make sense. Since a LocalTime is a time of day without date, there is no way to get a date out of it. But you can print the ZonedDateTime and verify its date part. And to assure yourself that the code is correct, write some unit tests.
Link: Oracle tutorial: Date Time explaining how to use java.time.
A simple approach might be to parse your time Strings to instances of LocalTime and compare them. You have to decide if the start and end time are inclusive or not...
Support some formattings because you might have to pass Strings with AM/PM or without:
public static boolean isInTimeSlot(String time, String timeSlotStart, String timeSlotEnd) {
// create a formatter that supports different formats for the String arguments
DateTimeFormatter parserDtf = DateTimeFormatter.ofPattern("[hh:mm:ss a][HH:mm:ss][h a]");
// parse each argument to a LocalTime
LocalTime timeOfDay = LocalTime.parse(time, parserDtf);
LocalTime fromTime = LocalTime.parse(timeSlotStart, parserDtf);
LocalTime toTime = LocalTime.parse(timeSlotEnd, parserDtf);
// and return if the given time is in the time slot (including start and end time)
return timeOfDay.equals(fromTime) || timeOfDay.equals(toTime)
|| (timeOfDay.isAfter(fromTime) && timeOfDay.isBefore(toTime));
}
If you run it in a main like this
public static void main(String[] args) {
// provide some sample times
String[] times = { "10:31:17", "09:59:59", "6 PM", "4 AM", "06:00:01 PM" };
// provide a time slot
String from = "10 AM";
String to = "6 PM";
// check the method for each time string
for (String time : times) {
if (isInTimeSlot(time, from, to)) {
System.out.println(time + " is in the time slot at or between "
+ from + " and " + to);
} else {
System.err.println(time + " is not in the time slot at or between "
+ from + " and " + to);
}
}
}
the output will be
10:31:17 is in the time slot at or between 10 AM and 6 PM
09:59:59 is not in the time slot at or between 10 AM and 6 PM
6 PM is in the time slot at or between 10 AM and 6 PM
4 AM is not in the time slot at or between 10 AM and 6 PM
06:00:01 PM is not in the time slot at or between 10 AM and 6 PM
All I want to check if the current time from any timezone falls under the range of 10 am to 6 pm. If Yes, print "yes" else print "no".
For this, the following code will do the job.
LocalTime lt = LocalTime.now();
if( lt.isAfter( LocalTime.of( 10, 0 ) ) && lt.isBefore( LocalTime.of( 18, 0 ) ) ) System.out.println( "Yes" );
else System.out.println( "No" );
Since you have Date instances with you, you can convert them into LocalTime instances as shown below and use the same mechanism of comparison.
Date d = new Date(); //Change this to your way of creating the Date instance
LocalTime lt = LocalDateTime.ofEpochSecond( d.getTime(), 0, ZoneOffset.ofHours( 0 ) ).toLocalTime();
Hope this helps.
I had a look at the java api about GregorianCalendar and did not see any way of setting the am/pm
in its constructor. Can you set AM/PM in a GregorianCalendar date or is it something you can only get using a get method on the calendar. Does it handle all of this automatically. I am looking to take the am/pm and output it in my toString for a class which has a date object. I was going to use the get method on the calendar to achieve this. I understand the am/pm is an int that is 0 or 1.
Are all hours in the 24 hour format in Gregorian and does it automatically determines the am and pm?
Calendar.get(Calendar.HOUR);
Gives the hour (0-12) for AM/PM format.
Calendar.get(Calendar.HOUR_OF_DAY);
Gives the hour ranging from 0-24.
It does the conversion on its own. You don't need to tell it.
cal.set( Calendar.AM_PM, Calendar.AM )
Will/Could change the point time this calendar object represents. (If it's 1:00PM you will have 1:00AM afterwards). This is true for GregorianCalendar (see comment to question by Peter Cetinski).
Btw/Hint imo you should use a DateFormat to ouput your preferred format.
Calendar cal = new GreogorianCalendar();
cal.set( Calendar.AM_PM, Calendar.AM );
Simply I did this :
Calendar calendar = new GregorianCalendar();
int seconds = calendar.get(Calendar.SECOND);
int minutes = calendar.get(Calendar.MINUTE);
int hour = calendar.get(Calendar.HOUR);
int am_pm = calendar.get(Calendar.AM_PM);
String ampm = "ampm";
if (am_pm == 0) {
ampm = "AM";
} else {
ampm = "PM";
}
jLabel1.setText(hour + ":" + minutes + ":" + seconds + " " + ampm);
What might be the Android equivalent of the following iPhone code?
NSCalendar *calender = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
int units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *components = [calender components:units fromDate:[NSDate date] toDate:destinationDate options:0];
I am trying to do a date countdown to show the number of years, months, days, hours, minutes and seconds in a consecutive manner, not show the years, months, days, hours, minutes and seconds as a whole.
I have this, but I cannot get the hours, minutes and seconds. When I play with the hours, I keep getting hours in the days, not hours left.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = format.parse(myDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long nat = Math.round(date.getTime() / 1000);
long totaldifference = Math.abs(d1-d2);
long date_diff = Math.round(totaldifference/(24*3600));
//year
double year2 = Math.floor(date_diff/365);
date_diff-=year2*365;
double month2 = Math.floor(date_diff/30.5);
date_diff-=month2*30.5;
long day2 = date_diff;
To get a Calendar, you can do this:
Calendar cal = Calendar.getInstance()
Doing it this way will initialize it to the current date and time. Check the documentation if you need to set it to a different date or time.
To get the year, month, day, and so on, you can do this:
int year = cal.get(Calendar.YEAR)
int month = cal.get(Calendar.MONTH)
int day = cal.get(Calendar.DATE)
To "count down" on that, you can add a negative of whatever unit you want to count down in:
cal.add(Calendar.SECOND, -1)
Have a look at the documentation for calendar it should help. You get the year, month, day etc all seperately so should be easy to implement your countdown. Its a base class so you should be able to extend it to do what you need.
Here is the code, for your viewing pleasure:
public static void main(String[] args) throws Exception {
Calendar cal = Calendar.getInstance();
cal.set(2010, Calendar.JULY, 10, 1, 0, 20);
Date d1 = cal.getTime();
Date d2 = new Date();
int seconds = 22;
d2.setTime(d1.getTime() - seconds*1000);
SimpleDateFormat iso_format = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
System.out.println(iso_format.format(d1) + " - " + seconds + "s = " + iso_format.format(d2));
}
Output: 2010-07-10 01:00:20 - 22s = 2010-07-10 24:59:58
Shouldn't the answer be 2010-07-09 24:59:58? Why does it loop back to the same day? Is there a way to fix it?
the hour 24 (since you used 'kk' to format) is considered the next day, ie the 10th. it is equivalent to midnight. I use 'HH' to format hours, which would display the 24th hour as '00'. this makes more sense to me and i believe is more standards compliant.
the date changes over at the 00/24th hour. if you were to subtract another hour from the resulting date, the date would become the 9th as expected.
also, if you want true ISO time format 'HH' is better than 'kk'.
http://en.wikipedia.org/wiki/ISO_8601#Times