How to increment time by 1 hour - java

I have two time values. one for the previous login time and one for the current login time.
I have to increase previous time login by one hour. I have used the date format hh:mm:ss.
This is my code snippet.
Date previous_time, current_time;
if(previous_time.before(current_time)){
Log.i("Time Comparision"," true");
}
so instead of the above mentioned if condition, I have to add one hour to the previous_time and do the if condition. How to achieve this?

Calendar calendar = Calendar.getInstance();
calendar.setTime(previous_time);
calendar.add(Calendar.HOUR, 1);
previous_time = calendar.getTime();
// do your comparison

previous_time.setTime(previous_time.getTime() + 60 * 60 * 1000);
or
Date session_expiry = new Date(previous_time.getTime() + 60 * 60 * 1000);
http://download.oracle.com/javase/6/docs/api/java/util/Date.html#getTime%28%29

Please try this code.
SimpleDateFormat sdf = new SimpleDateFormat("h:mm a");
Date date = Utils.getBookingDate(mBooking.ToTime);
Calendar calendarAdd = Calendar.getInstance();
calendarAdd.setTime(date);
calendarAdd.add(Calendar.HOUR, 1);
toTime = sdf.format(calendarAdd.getTime());
tv_Totime.setText(toTime);
when current time string formate within add 1 hours

Related

Set new time after the actual one

I'm trying to create a method that prints e.g. actual time of arrival (now) and then it prints the time of departure which I want to set plus 3 minutes compared to the first one.
public void updateTimes(){
SimpleDateFormat sdf = new SimpleDateFormat("H:mm");
this.arrivalTime = new Date();
this.departureTime = this.arrivalTime.plusMinutes(3);
}
Departure time doesn't work as intended.
Any help is welcome.
java.util.Date not have plusMinutes.
It can be better if you use Java 8, with java.time library :
LocalTime arrivalTime = LocalTime.now();//Current time
LocalTime departureTime = arrivalTime.plusMinutes(3);//plus 3 minutes to the time
//Then you can format the time
String result = departureTime.format(DateTimeFormatter.ofPattern("H:mm"));
Another solution using Calendar looks like:
Calendar cal = Calendar.getInstance();
cal.setTime(arrivalTime); // only if different from "now"
cal.add(Calendar.MINUTE, 3);
departureTime = cal.getTime();
I think you can do something like below:
SimpleDateFormat sdf = new SimpleDateFormat("H:mm");
Date date = new Date();
System.out.println("arrival time = " + sdf.format(date));
int min = date.getMinutes();
date.setMinutes(min+3);
System.out.println("departure time = " + sdf.format(date));

Span in days between two dates misunderstanding

I have a misundertood managing dates in Java when I want to calculate the span in number of days between two dates.
Say we have two different dates:
Date 1: 1986-01-24
Date 2: 2017-04-20
Case 1: I have this snippet of code using Dates:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date dt1 = format.parse("1986-01-24");
Date dt2 = format.parse("2017-04-20");
int intSpanInDays= (int) ((dt2.getTime() - dt1.getTime()) / (1000 * 60 * 60 * 24));
System.out.println("Days between: " + intSpanInDays);
Output 1:
Days between: 11408
Case 2: Snippet of code using Calendar:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
GregorianCalendar cal1 = new GregorianCalendar();
cal1.setTime(format.parse("1986-01-24"));
cal1.set(Calendar.HOUR, 0);
cal1.set(Calendar.MINUTE, 0);
cal1.set(Calendar.SECOND, 0);
GregorianCalendar cal2 = new GregorianCalendar();
cal2.setTime(format.parse("2017-04-20"));
cal2.set(Calendar.HOUR, 0);
cal2.set(Calendar.MINUTE, 0);
cal2.set(Calendar.SECOND, 0);
long spanInMillis = cal2.getTimeInMillis() - cal1.getTimeInMillis();
GregorianCalendar cal3 = new GregorianCalendar();
cal3.setTimeInMillis(spanInMillis);
long millisInADay = 1000 * 60 * 60 * 24;
System.out.println("Days between: " + (cal3.getTimeInMillis() / millisInADay));
Output 2:
Days between: 11408
Case 3: Example using a spreadsheet in Excel:
When I use MS Excel to get this span just introducing the given dates and simply substracting, the output is this:
QUESTION
Why is Java calculation code of date missing one day? What is missing or wrong in either case 1 and 2 that does not match the result in case 3?
The spreadsheet is taking Daylight Savings into account, and your calculations are naively truncating, and given that there's one more 23-hour day in the interval than 25-hour days, the 23-hour remainder is truncated, yielding a result one day less than the correct answer.
JDK 8 largely simplifies these calculations with its new date time API. The same can be done accurately and simply using the below code :
LocalDate date1 = LocalDate.of(1986, 01, 24);
LocalDate date2 = LocalDate.of(2017, 04, 20);
System.out.println(date1.until(date2, ChronoUnit.DAYS));
This automatically takes care of any/all the DST changes, leap years etc. which is mostly missed when trying to do the calculations manually.

Check if current time is between 2 times. JAVA

I'm new at coding and I want my program to do something if the current time is between 2 times.
Example:
Current time = 8:25AM
If current time is between 8:00AM and 8:50AM, print 'something' into console.
Is there a way for my program to get the current time automatically? Calendar Class?
Please Help!
Matthew
You can get current time instantiating a new java.util.Object
Date current = new Date();
Then you can play with after() and before() methods
Hope this helps,
Alberto
String starttime = "08:00:00";
String endtime = "08:50:00";
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(starttime);
Date date2 = format.parse(endtime);
Calendar cal = Calendar.getInstance();
String currenttime = format.format(cal.getTime());
Date datenow = format.parse(currenttime)
if (date1.getTime() < datnow.getTime() && date2.getTIme() > datenow.getTime())
System.out.println("Time is within defined borders.");
I dont have a compiler now . This should work fine .

How to add current time to a previous date in java?

I was trying to add current time into previous date. But it was adding in current date with time not with previous date.
see my bellow code:
Date startUserDate = ;//this is my previous date object;
startUserDate.setTime(new Date().getTime());// here i'm trying to add current time in previous date.
System.out.println("current time with previous Date :"+startUserDate);
In previous date there is no time and i want to add current time in previous date.I can do this, please help me out.
Use calendar object
Get instance of calendar object and set your past time to it
Date startUserDate = ;
Calendar calendar = Calendar.getInstance();
calendar.settime(startUserDate);
Create new calendar instance
Calendar cal = Calendar.getInstance();
cal.settime(new Date());
format the date to get string representation of time of current date
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String currentdate = sdf.format(cal.getTime());
split that string to get hour minute and second object
String hh = expiry.split(":")[0];
String mm = expiry.split(":")[1];
String ss = expiry.split(":")[2];
add it to the previous calendar object
calendar .add(Calendar.HOUR_OF_DAY, hh);
calendar .add(Calendar.MINUTE, mm);
calendar .add(Calendar.SECOND, ss);
this date will have current time added to your date
Date newDate = calendar.getTime;
Use Calendar:
first set the date/time of the first calendar object to the old date
object use as second Calendar object to set the current time on the
first calendar object then convert it back to date
as follow:
//E.g. for startUserDate
Date startUserDate = new Date(System.currentTimeMillis() - (24L * 60L * 60L * 1000L) - (60L * 60L * 1000L));//minus 1 day and 1 hour
Calendar calDateThen = Calendar.getInstance();
Calendar calTimeNow = Calendar.getInstance();
calDateThen.setTime(startUserDate);
calDateThen.set(Calendar.HOUR_OF_DAY, calTimeNow.get(Calendar.HOUR_OF_DAY));
calDateThen.set(Calendar.MINUTE, calTimeNow.get(Calendar.MINUTE));
calDateThen.set(Calendar.SECOND, calTimeNow.get(Calendar.SECOND));
startUserDate = calDateThen.getTime();
System.out.println(startUserDate);
The second Calendar object calTimeNow can be replaced with Calendar.getInstance() where it is used.
You can do it using DateFormat and String, here's the solution that you need:
Code:
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String timeString = df.format(new Date()).substring(10); // 10 is the beginIndex of time here
DateFormat df2 = new SimpleDateFormat("MM/dd/yyyy");
String startUserDateString = df2.format(startUserDate);
startUserDateString = startUserDateString+" "+timeString;
// you will get this format "MM/dd/yyyy HH:mm:ss"
//then parse the new date here
startUserDate = df.parse(startUserDateString);
Explanation:
Just convert the current date to a string and then extract the time from it using .substring() method, then convert your userDate to a string concatenate the taken time String to it and finally parse this date to get what you need.
Example:
You can see it working in this ideone DEMO.
Which takes 02/20/2002 in input and returns 02/20/2002 04:36:14 as result.
java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work.
ZoneId zone = ZoneId.systemDefault();
LocalDate somePreviousDate = LocalDate.of(2018, Month.NOVEMBER, 22);
LocalTime timeOfDayNow = LocalTime.now(zone);
LocalDateTime dateTime = somePreviousDate.atTime(timeOfDayNow);
System.out.println(dateTime);
When I ran the code just now — 16:25 in my time zone — I got this output:
2018-11-22T16:25:53.253892
If you’ve got an old-fashioned Date object, start by converting to a modern Instant and perform further conversion from there:
Date somePreviousDate = new Date(1_555_555_555_555L);
LocalDate date = somePreviousDate.toInstant().atZone(zone).toLocalDate();
LocalTime timeOfDayNow = LocalTime.now(zone);
LocalDateTime dateTime = date.atTime(timeOfDayNow);
2019-04-18T16:25:53.277947
If conversely you need the result as an old-fashioned Date, also convert over Instant:
Instant i = dateTime.atZone(zone).toInstant();
Date oldfasionedDate = Date.from(i);
System.out.println(oldfasionedDate);
Thu Nov 22 16:25:53 CET 2018
Link
Oracle tutorial: Date Time explaining how to use java.time.
The getTime method returns the number of milliseconds since 1970/01/01 so to get the time portion of the date you can either use a Calendar object or simply use modula arithmetic (using the above milliseconds value and the MAX millseconds in a day) to extract the time portion of the Date.
Then when you have the time you need to add it to the second date,
but seriously, use http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
and use things like get (HOUR) and get (MINUTE) etc. which then you can use with set (HOUR, val)
You need to use Calendar class to perform addition to Dateobject. Date's setTime() will set that time in Date object but not add i.e it will overwrite previous date. new Date().getTime() will not return only time portion but time since Epoch. Also, how did you manipulated , startUserDate to not have any time (I mean , was it via Calendar or Formatter) ?
See Answer , Time Portion of Date to calculate only time portion,
long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
Date now = Calendar.getInstance().getTime();
long timePortion = now.getTime() % MILLIS_PER_DAY;
then you can use something like, cal.add(Calendar.MILLISECOND, (int)timePortion); where cal is Calendar object corresponding to your startUserDate in your code.
Calendar calendar = Calendar.getInstance();
calendar.setTime(startUserDate );
//new date for current time
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String currentdate = sdf.format(new Date());
String hhStr = currentdate.split(":")[0];
String mmStr = currentdate.split(":")[1];
String ssStr = currentdate.split(":")[2];
Integer hh = 0;
Integer mm = 0;
Integer ss = 0;
try {
hh = Integer.parseInt(hhStr);
mm = Integer.parseInt(mmStr);
ss = Integer.parseInt(ssStr);
}catch(Exception e) {e.printStackTrace();}
calendar.set(Calendar.HOUR_OF_DAY, hh);
calendar.set(Calendar.MINUTE, mm);
calendar.set(Calendar.SECOND, ss);
startUserDate = calendar.getTime();

Get date in past using java.util.Date

Below is code I am using to access the date in past, 10 days ago. The output is '20130103' which is today's date. How can I return todays date - 10 days ? I'm restricted to using the built in java date classes, so cannot use joda time.
package past.date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class PastDate {
public static void main(String args[]){
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date myDate = new Date(System.currentTimeMillis());
Date oneDayBefore = new Date(myDate.getTime() - 10);
String dateStr = dateFormat.format(oneDayBefore);
System.out.println("result is "+dateStr);
}
}
you could manipulate a date with Calendar's methods.
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
Date myDate = new Date(System.currentTimeMillis());
System.out.println("result is "+ dateFormat.format(myDate));
Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
cal.add(Calendar.DATE, -10);
System.out.println(dateFormat.format(cal.getTime()));
This line
Date oneDayBefore = new Date(myDate.getTime() - 10);
sets the date back 10 milliseconds, not 10 days. The easiest solution would be to just subtract the number of milliseconds in 10 days:
Date tenDaysBefore = new Date(myDate.getTime() - (10 * 24 * 60 * 60 * 1000));
Use Calendar.add(Calendar.DAY_OF_MONTH, -10).
The class Date represents a specific instant in time, with millisecond precision.
Date oneDayBefore = new Date(myDate.getTime() - 10);
So here you subtract only 10 milliseconds, but you need to subtract 10 days by multiplying it by 10 * 24 * 60 * 60 * 1000
You can also do it like this:
Date tenDaysBefore = DateUtils.addDays(new Date(), -10);
Date today = new Date();
Calendar cal = new GregorianCalendar();
cal.setTime(today);
cal.add(Calendar.DAY_OF_MONTH, -30);
Date today30 = cal.getTime();
System.out.println(today30);

Categories