How to add current time to a previous date in java? - 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();

Related

how to get dateTime based on hour and minute

I have hour and minute in edittext.(say for example 10:50)
how to get today's DateTime(like yyyy-MM-dd HH:mm:ss) based on above edit text value 10:50
UPDATE:
this worked for me:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, selectedHour);
calendar.set(Calendar.MINUTE, selectedMinute);
thank you all
EDIT: take a look at this other stackoverflow post about why one should prefer using the Java 8 java.time classes over Calendar or Date
In your instance, in order to parse an input in the form "HH:mm", you can create a DateTimeFormatter and use the static method LocalTime.parse(inputString, dateTimeFormatter) to get a LocalTime object
For example:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
LocalTime time = LocalTime.parse(timeInputString, formatter);
Take a look at the Java documentation for DateTimeFormatter for more information on the patterns for years, days, or whatever.
If you're wanting to get both the date and time from a string such as "10:50", you won't be able to using the LocalDateTime.parse method because it can't obtain the date from an "HH:mm" string. So the way around this is to create the time off of LocalTime.parse as shown above, and then get the current date using the static method LocalDate.now(); And then combine those two results into a LocalDateTime object using it's static factory method LocalDateTime.of(date, time)
For example:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
LocalTime time = LocalTime.parse(timeInputString, formatter);
LocalDate date = LocalDate.now();
LocalDateTime dateTime = LocalDateTime.of(date, time);
Calendar cal = new Calendar.getInstance();// today's date
cal.set(Calendar.HOUR, 10);
cal.set(Calendar.MINUTE, 50);
cal.set(Calendar.SECOND, 0);
System.out.println(cal.getTime()); //see the result
now , it's up to you to put them directly in cal.set with variables (not manually writing 10 ,50 , it's up to your creativity )
And this answer is with Calendar because you tagged Calendar in your question , you can also use something else than Calender
you just need use this function.
// hourMintText = "hh:mm"
private String getTodayAsFormat(String hourMintText){
String[] hourMinAsArray = hourMintText.split(":");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hourMinAsArray[0]));
calendar.set(Calendar.MINUTE, Integer.parseInt(hourMinAsArray[1]));
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm", Locale.ENGLISH);
return simpleDateFormat.format(calendar.getTimeInMillis());
}
Try this:
String dateTime = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss aa", Locale.getDefault())
.format(new Date());

How to save iso8601 Date in Java?

I need to save the current Date + 7 days in iso8601 format as following:
20161107T12:00:00+0000
Where the part after the "T" is fixed.
I tried the following:
Calendar exDate1 = Calendar.getInstance();
exDate1.add(Calendar.DATE , 7);
Date Date1 = exDate1.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMDD");
String Date = sdf.format(Date1 + "T12:00:00+0000");
With no success.
Another way is using the new java.time-API in Java-8:
String result =
DateTimeFormatter.BASIC_ISO_DATE.format(
LocalDate.now(ZoneOffset.UTC).plusDays(7)
) + "T12:00:00+0000";
System.out.println(result); // 20161114T12:00:00+0000
Update due to your choice of timezone offset:
You tried to implicitly use the system timezone to determine the current local time but apply a fixed offset of UTC+0000. This is an inconsistent combination. If you apply such a zero offset then you should also determine the current date according to UTC+0000, not in your system timezone (ZoneId.systemDefault()).
The proposal of editor #Nim
Alternatively - the string above may not have the correct offset:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HH:mm:ssZ");
String date = LocalDate.now().plusDays(7).atTime(12, 0).atZone(ZoneId.systemDefault()).format(formatter);
would yield the result:
20161114T12:00:00+0100
which is probably not what you want. I also try to avoid the expression LocalDate.now() without any arguments because it hides the dependency on the system timezone.
use this 'yyyyMMdd'pattern
Calendar currentDate = Calendar.getInstance();
currentDate.add(Calendar.DATE, 7);
Date date = currentDate.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String formattedDate = sdf.format(date).concat("T12:00:00+0000");

how to compare two calendar objects?

I want to compare two date objects like this:
String format = "MM/dd/yyyy hh:mm a";
SimpleDateFormat sdf = new SimpleDateFormat(format);
fakeDate = sdf.parse("15/07/2013 11:00 AM");
fakeDate2 = sdf.parse("15/07/2013 12:00 AM");
int diff = date2.getHours() - date1.getHours();
but then I see getHours is deprecated.
So i have used:
Calendar calendar1 = Calendar.getInstance();
calendar.setTime(new Date("15/7/2013 11:00AM"));
Calendar calendar2 = Calendar.getInstance();
calendar.setTime(new Date("11/7/2013 12:00AM"));
calendar1.get(Calendar.HOUR_OF_DAY) - calendar2.get(Calendar.HOUR_OF_DAY)
but then I see the diff is zero. I guess i change the same calendar instance all the time and compare it to itself. no?
how would you write this?
new Date("15/7/2013 11:00AM")
is not the correct way to construct a Date object. It's deprecated also. Use proper SimpleDateFormat as you are doing well in your first example.
The format MM/dd/yyyy hh:mm a is not correct as per the input date string.
It should be like this.
String format = "dd/MM/yyyy hh:mm a";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date fakeDate = sdf.parse("15/07/2013 11:00 AM");
Date fakeDate2 = sdf.parse("15/07/2013 12:00 AM");
Calendar cal = Calendar.getInstance();
cal.setTime(fakeDate); //set time to first date
int hours1 = cal.get(Calendar.HOUR); // get the hours
cal.setTime(fakeDate2); // set time to second date
int hours2 = cal.get(Calendar.HOUR); // get the hours
System.out.println(hours1 - hours2); // 11 hours
You seemed really confused though it is depreciated this code shall give you a difference of 11 hours which makes sense
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
Date fakeDate = dateFormat.parse("15/07/2013 11:00 AM");
Date fakeDate2 = dateFormat.parse("15/07/2013 12:00 AM");
System.out.println(fakeDate.getHours()-fakeDate2.getHours());
Or if you are so interested to use Calendar do it this way
Calendar calendar = Calendar.getInstance();
calendar.setTime(fakeDate);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(fakeDate2);
System.out.println(calendar.get(Calendar.HOUR_OF_DAY) -
calendar2.get(Calendar.HOUR_OF_DAY));
You will get the same 11 hours difference or simply do it this way
long millisForNewDate = toDate.getTime();
long millisForOldDate = fromDate.getTime();
long difference = millisForNewDate - millisForOldDate;
int hoursDifferenceBetweenDates = (int)(difference/(1000*60*60));

Calendar Conversion between Different TimeZones in Java

I want to convert the calendar object between two time zones in java.I shall the pass the first calendar object and want the output to be the modified calendar object with the different timezone.
Can someone provide me a way on how to do it ?
This is what i have done ...
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
GregorianCalendar pst = new GregorianCalendar();
GregorianCalendar est = new GregorianCalendar();
pst.setTime(maintWindow);
int year = pst.get(Calendar.YEAR);
int month = pst.get(Calendar.MONTH);
int day = pst.get(Calendar.DAY_OF_MONTH);
format.setTimeZone(timeZone);
pst.set(year, month, day, hour, min);
Date date = pst.getTime();
logger.info(date);
logger.info(format.format(date));
logger.info(pst.getTime());
est.setTimeInMillis(date.getTime());
logger.info(est.getTime());
You can use Calendar.setTimeZone.
For example if you have a Calendar reference cal initialized with any time zone, a call to the method like this
cal.setTimeZone(TimeZone.getTimeZone("GMT"))
modifies the time zone of cal to GMT.

How to subtract X day from a Date object in Java?

I want to do something like:
Date date = new Date(); // current date
date = date - 300; // substract 300 days from current date and I want to use this "date"
How to do it?
Java 8 and later
With Java 8's date time API change, Use LocalDate
LocalDate date = LocalDate.now().minusDays(300);
Similarly you can have
LocalDate date = someLocalDateInstance.minusDays(300);
Refer to https://stackoverflow.com/a/23885950/260990 for translation between java.util.Date <--> java.time.LocalDateTime
Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
Java 7 and earlier
Use Calendar's add() method
Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();
#JigarJoshi it's the good answer, and of course also #Tim recommendation to use .joda-time.
I only want to add more possibilities to subtract days from a java.util.Date.
Apache-commons
One possibility is to use apache-commons-lang. You can do it using DateUtils as follows:
Date dateBefore30Days = DateUtils.addDays(new Date(),-30);
Of course add the commons-lang dependency to do only date subtract it's probably not a good options, however if you're already using commons-lang it's a good choice. There is also convenient methods to addYears,addMonths,addWeeks and so on, take a look at the api here.
Java 8
Another possibility is to take advantage of new LocalDate from Java 8 using minusDays(long days) method:
LocalDate dateBefore30Days = LocalDate.now(ZoneId.of("Europe/Paris")).minusDays(30);
Simply use this to get date before 300 days, replace 300 with your days:
Date date = new Date(); // Or where ever you get it from
Date daysAgo = new DateTime(date).minusDays(300).toDate();
Here,
DateTime is org.joda.time.DateTime;
Date is java.util.Date
Java 8 Time API:
Instant now = Instant.now(); //current date
Instant before = now.minus(Duration.ofDays(300));
Date dateBefore = Date.from(before);
As you can see HERE there is a lot of manipulation you can do. Here an example showing what you could do!
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
//Add one day to current date.
cal.add(Calendar.DATE, 1);
System.out.println(dateFormat.format(cal.getTime()));
//Substract one day to current date.
cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
System.out.println(dateFormat.format(cal.getTime()));
/* Can be Calendar.DATE or
* Calendar.MONTH, Calendar.YEAR, Calendar.HOUR, Calendar.SECOND
*/
With Java 8 it's really simple now:
LocalDate date = LocalDate.now().minusDays(300);
A great guide to the new api can be found here.
In Java 8 you can do this:
Instant inst = Instant.parse("2018-12-30T19:34:50.63Z");
// subtract 10 Days to Instant
Instant value = inst.minus(Period.ofDays(10));
// print result
System.out.println("Instant after subtracting Days: " + value);
I have created a function to make the task easier.
For 7 days after dateString: dateCalculate(dateString,"yyyy-MM-dd",7);
To get 7 days upto dateString: dateCalculate(dateString,"yyyy-MM-dd",-7);
public static String dateCalculate(String dateString, String dateFormat, int days) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat s = new SimpleDateFormat(dateFormat);
try {
cal.setTime(s.parse(dateString));
} catch (ParseException e) {
e.printStackTrace();
}
cal.add(Calendar.DATE, days);
return s.format(cal.getTime());
}
You may also be able to use the Duration class. E.g.
Date currentDate = new Date();
Date oneDayFromCurrentDate = new Date(currentDate.getTime() - Duration.ofDays(1).toMillis());
You can easily subtract with calendar with SimpleDateFormat
public static String subtractDate(String time,int subtractDay) throws ParseException {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
cal.setTime(sdf.parse(time));
cal.add(Calendar.DATE,-subtractDay);
String wantedDate = sdf.format(cal.getTime());
Log.d("tag",wantedDate);
return wantedDate;
}

Categories