Android/Java: Time calculations - java

Im using the following code in my android app to get the current time
SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
String time = dateFormatLocal.format(new Date());
I would like to know if theres an easy way to check timespans, for example if the clock is between 19:00 and 21:00. Thanks

There's nothing wrong with Chris's method, but here's another option:
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
if (hour >= 19 && hour < 21) {
System.out.println("WIN");
}
Then you can construct your string with:
String time = dateFormatLocal.format(now.getTime() );
I'll leave it to the next poster to point out that you can also use Joda-Time. :)

This might not be the most efficient solution (as I think you could probably do it with the Date objects) but what about
SimpleDateFormat df = new SimpleDateFormat("HH");
String hours = df.format(new Date());
Integer number = Integer.parseInt(hours);
if (numbers >= 19 && numbers <= 20){
//good
}else{
//not good
}

Related

Get current time and check if time has passed a certain period

this code below gets the current time and timezone of the area
Date date = new Date();
DateFormat df = new SimpleDateFormat("HH:mm:ss");
df.setTimeZone(TimeZone.getDefault());
System.out.println("Time: " + df.format(date));
right now its 1:01 pm (at the time of typing)
what i need help doing is implementing a feature in the code that checks if the current time has passed, for example 1:00PM
but I have no idea where to even start, can you help me out?
Use the Java 8+ Time API class LocalTime:
LocalTime refTime = LocalTime.of(13, 0); // 1:00 PM
// Check if now > refTime, in default time zone
LocalTime now = LocalTime.now();
if (now.isAfter(refTime)) {
// passed
}
// Check if now >= refTime, in pacific time zone
LocalTime now = LocalTime.now(ZoneId.of("America/Los_Angeles"))
if (now.compareTo(refTime) >= 0) {
// passed
}
I see it has already answered with Time, but as a teaching point, if you really wanted to use Date, you could have done something like this:
public static void main(String[] args) {
Date date = new Date();
DateFormat df = new SimpleDateFormat("HH:mm:ss");
df.setTimeZone(TimeZone.getDefault());
System.out.println("Time: " + df.format(date));
//If you print the date you'll see how it is formatted
//System.out.println(date.toString());
//So you can just split the string and use the segment you want
String[] fullDate = date.toString().split(" ");
String compareAgainstTime = "01:00PM";
System.out.println(isPastTime(fullDate[3],compareAgainstTime));
}
public static boolean isPastTime(String currentTime, String comparedTime) {
//We need to make the comparison time into the same format as the current time: 24H instead of 12H:
//then we'll just convert the time into only minutes to that we can more easily compare;
int comparedHour = comparedTime[-2].equals("AM") ? String.valueOf(comparedTime[0:2]) : String.valueOf(comparedTime[0:2] + 12 );
int comparedMin = String.valueOf(comparedTime[3:5]);
int comparedT = comparedHour*60 + comparedMin;
//obviously currentTime is alredy the correct format; just need to convert to minutes
int currentHour = String.valueOf(currentTime[0:2]);
int currentMin = String.valueOf(currentTime[3:5]);
int currentT = currentHour*60 + currentMin;
return (currentT > comparedT);
}
It's a bit messier, having to muddy into the Strings and whatnot, but it is possible. You would also have to be careful the zero-pad the comparedTime or just check for that in the function

Display and save only hours in int

How to display only hours and using int variable? I mean print time like 20:30:44 PM, I want to store only hours, mean 20 in int variable. how to do that?
Can anybody tell me the code if you know, thanks?
Try using Calendar's get method like:
Calendar c = ..
c.setTime(...);//if you have time in long coming from somewhere else
int hour = c.get(Calendar.HOUR_OF_DAY);
If you try to parse time from String I recommend these solutions:
String time = "20:30:44 PM"; // this is your input string
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss aa");
try {
Date date = sdf.parse(time);
// this is the uglier solution
System.out.println("The hour is: "+date.getHours());
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(date);
// this is nicer solution
System.out.println("The hour is: "+gc.get(Calendar.HOUR_OF_DAY));
} catch (ParseException e) {
System.err.println("Couldn't parse string! "+e.getMessage());
}
date.getHours() and gc.get(Calendar.HOUR_OF_DAY) return int, in this example I printed it out without creating variable.
You can, of course, use regular expression to find out hour in your string but above solutions should do the trick. You can learn more about SimpleDateFormat and available patterns here. I hope I helped you a bit.
EDIT: In his comment autor noted, that date isn't static (like in String) but dynamic:
Calendar calendar = new GregorianCalendar();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
System.out.println("The hour is: "+hour);
I hope this helps.

Change Days to Dates in Timetable for Android

Here is code to show Mon-Fri . I do not want to show the Days (Mon-Fri). I want to show the Dates (DD-MMM-YYY). How can I change my code. Please help me take a look.Thanks.
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK);
pager.setAdapter(buildAdapter(res));
if (day == 1)
{
int finalDay = 6;
pager.setCurrentItem(finalDay);
}
else
{
int finalDay = day - 2;
pager.setCurrentItem(finalDay);
}
pager.setOffscreenPageLimit(7);
Here is the ScreenShot:
You can use SimpleDateFormat class to show the dates like this:
String pattern="dd-MMM-yyy";
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.applyPattern(pattern);
String format = sdf.format(Calendar.getInstance().getTime());

Add hours and Minutes to a certain time java

I have String initialTime= "10:30:00"
I am converting it into time like so:-
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = sdf.parse(initialTime);
Time time = new Time(date.getTime());
int initHour = time.getHours()
int initMind = time.getMinutes();
Further I have two values;
int hour, mins;
The hour value can be anything from 0-10;
mins value can be 0,15,30,45.
The user selects a time by selecting hour and mins. As soon as the user selects the values they should get added to the initialTimeand shown in finalTIme
So if:-
hour=0 and mins=15 then finalTIme=10:45:00
hour=0 and mins=35 then finalTIme=11:00:00
hour=0 and mins=45 then finalTIme=11:15:00
I tried doing something like:-
if(hour==0 && mins==0)
{
finalTime = initialTime;
}
else if(hour==0 && mins>0 && mins <30)
{
mins = initMins + mins
}
else if(hour==0 && mins>0 && mins >=30)
{
hours = hours+1;
mins = mins-60;
}
But I did not get the required output. HOw can I do it in a less complicated manner?
You can use java.util.Calendar class:
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = sdf.parse(initialTime);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR_OF_DAY, hours);
cal.add(Calendar.MINUTE, minutes);
date = cal.getTime();
You might also consider the new Date API from JDK 8.

Can you set AM/PM in a GregorianCalendar date or is it something you can only get

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);

Categories