Get date in past using java.util.Date - java

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

Related

How add 30 days in current date? [duplicate]

This question already has answers here:
Is SimpleDateFormat in Java work incorrect or I did any mistake? See code sample [duplicate]
(2 answers)
Parsing a string to date format in java defaults date to 1 and month to January
(2 answers)
Closed 3 years ago.
I want to add 30 days in my current date I searched a lot but did not get the proper solution.
my code
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd");
Calendar c1 = Calendar.getInstance();
String currentdate = df.format(date);
try {
c1.setTime(df.parse(currentdate));
c1.add(Calendar.DATE, 30);
df = new SimpleDateFormat("yyyy-MM-dd");
Date resultdate = new Date(c1.getTimeInMillis());
String dueudate = df.format(resultdate);
Toast.makeText(this, dueudate, Toast.LENGTH_SHORT).show();
} catch (ParseException e) {
e.printStackTrace();
}
The output of this code is :
2019-01-29
I don't why it is showing this output can anyone help me.
You need to use
c1.add(Calendar.DAY_OF_YEAR, 30);
instead of
c1.add(Calendar.DATE, 30);
Try this
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd");
Calendar c1 = Calendar.getInstance();
String currentDate = df.format(date);// get current date here
// now add 30 day in Calendar instance
c1.add(Calendar.DAY_OF_YEAR, 30);
df = new SimpleDateFormat("yyyy-MM-dd");
Date resultDate = c1.getTime();
String dueDate = df.format(resultDate);
// print the result
Utils.printLog("DATE_DATE :-> "+currentDate);
Utils.printLog("DUE_DATE :-> "+dueDate);
OUTPUT
2019-06-04 14:43:02.438 E/XXX_XXXX: DATE_DATE :-> 2019-06-04
2019-06-04 14:43:02.438 E/XXX_XXXX: DUE_DATE :-> 2019-07-04
Another easier option, if on Java 8, use the java.time package which provides functions to perform plus/minus on current date of any units of time, example:
import java.time.LocalDate;
LocalDate date = LocalDate.now().plusDays(30);
//or
LocalDate date = LocalDate.now().plus(30, ChronoUnit.DAYS);
Calendar.getInstance() gives you the current time. You don't need to create another Date object for that.
Calendar current = Calendar.getInstance();
current.add(Calendar.DATE, 30);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date resultdate = new Date(current.getTimeInMillis());
String dueudate = df.format(resultdate);
System.out.println("" + dueudate);
1)Go from date to millis.
2)Create a long variable with value 30L * 24L * 60L * 60L * 1000L.
3)Add this value to the millis you got in step 1
4) Go from this sum back to date again.
Edit: Variables that store millis should be long, not int.
Edit2: Adding "L" besides each number guarantees we won't get an overflow.

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

Subtracting dates and get difference in days.How to subtract them? [duplicate]

This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 8 years ago.
can anyone tell how to subtract string "after" from "today" to get days difference.
import java.text.*;
import java.util.*;
public class Main {
public static void main(String args[]){
SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
Calendar cal=Calendar.getInstance();
String today=sdf.format(cal.getTime());
System.out.println(today);
cal.add(Calendar.DATE, 20);
String After=sdf.format(cal.getTime());
System.out.println(After);
}
}
It would be easier with java8 where you dont need to subtract long values represent of date and change back to days, hours and minutes.
Date today= LocalDate.now();
Date futureDate = LocalDate.now().plusDays(1);
long days = Period.between(today, futureDate).getDays();
Period & LocalDate class are available in #java8
LocalDate docs
LocalDate is an immutable date-time object that represents a date,
often viewed as year-month-day. Other date fields, such as
day-of-year, day-of-week and week-of-year, can also be accessed. For
example, the value "2nd October 2007" can be stored in a LocalDate.
If you are not using java8, use joda-time library's org.joda.time.Days utility to calculate this
Days day = Days.daysBetween(startDate, endDate);
int days = d.getDays();
Using JodaTime, in case you don't have Java 8
String timeValue = "2014/11/11";
DateTimeFormatter parseFormat = new DateTimeFormatterBuilder().appendPattern("yyyy/MM/dd").toFormatter();
LocalDate startDate = LocalDate.parse(timeValue, parseFormat);
LocalDate endDate = startDate.plusDays(20);
System.out.println(startDate + "; " + endDate);
Period p = new Period(startDate, endDate);
System.out.println("Days = " + p.getDays());
System.out.println("Weeks = " + p.getWeeks());
System.out.println("Months = " + p.getMonths());
Which outputs...
2014-11-11; 2014-12-01
Days = 6
Weeks = 2
Months = 0
try this...
May it helps you.
import java.util.Date;
import java.util.GregorianCalendar;
// compute the difference between two dates.
public class DateDiff {
public static void main(String[] av) {
/** The date at the end of the last century */
Date d1 = new GregorianCalendar(2010, 10, 10, 11, 59).getTime();
/** Today's date */
Date today = new Date();
// Get msec from each, and subtract.
long diff = today.getTime() - d1.getTime();
System.out.println("The 21st century (up to " + today + ") is "
+ (diff / (1000 * 60 * 60 * 24)) + " days old.");
}
}
This may help You..
SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
Calendar cal=Calendar.getInstance();
String today=sdf.format(cal.getTime());
System.out.println(today);
cal.add(Calendar.DATE, 20);
String After=sdf.format(cal.getTime());
System.out.println(After);
Date d1 = null;
Date d2 = null;
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
try {
d1 = format.parse(today);
d2 = format.parse(After);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long diff = d2.getTime() - d1.getTime();
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("Difference is "+diffDays+" Days");

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

How to increment time by 1 hour

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

Categories