how to get the timestamp of previous dates in java? [duplicate] - java

This question already has answers here:
How to subtract n days from current date in java? [duplicate]
(5 answers)
Closed 9 years ago.
In my shopping cart application, I am storing all the purchase dates in timestamp.
Suppose, I want to get the timestamp of purchase date n days before (n is configurable). How will I get it using java?
example: something like
purchasedateBefore5days = currentTimestamp_in_days - 5;
I am getting current timestamp using
long currentTimestamp = Math.round(System.currentTimeMillis() / 1000);
How can i subtract n days from it. I am a beginner. Please help on this.

Use the Calendar class:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, -5);
long fiveDaysAgo = cal.getTimeInMillis();

You can use the Calendar class in Java , use its set() method to add/subtract the required number of days from the Calendar.DATE field.
To subtract n days from today , Use c.get(Calendar.DATE)-n. Sample code :
Calendar c = Calendar.getInstance();
System.out.println(c.getTime()); // Tue Jun 18 17:07:45 IST 2013
c.set(Calendar.DATE, c.get(Calendar.DATE)-5);
System.out.println(c.getTime()); // Thu Jun 13 17:07:45 IST 2013

Date d = initDate();//intialize your date to any date
Date dateBefore = new Date(d.getTime() - n * 24 * 3600 * 1000 ); //Subtract n days
Also possible duplicate .

That currentTimestamp must be passed to a Calendar instance.
from Calendar you can subtract X days.
Get the milliseconds from calendar and is done.

You can play aorund with the following code snippet, to form it the way you want:
Calendar c = Calendar.getInstance();
c.setTimeInMillis(milliSeconds);
c.add(Calendar.DATE, -5);
Date date = c.getTime();

Calendar calendar=Calendar.getInstance();
calendar.add(Calendar.DATE, -5);
using Java.util.Calendar Class
Calendar.DATE
This is the field number for get and set indicating the day of the month. , to subtract 5 days from the current time of the calendar, you can achieve it by calling.

Try this..
long timeInMillis = System.currentTimeMillis();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timeInMillis);
cal.set(Calendar.DATE, cal.get(Calendar.DATE)-5);
java.util.Date date1 = cal.getTime();
System.out.println(date1);

Related

math with dates , + - and ADD

Hello guys i have a tricky question for you that i really cant find a solution out there.
What i want to do is to have 3 date/time inputs on simpledateformat
Date 1
Date 2
Date 3
and basicaly i want to get difference of months days hours and minutes from date 1 - date2 and result of those 2 dates to be added on the firth date
for example 11/3/2017 12:30 - 7/3/2017 = 4 days and ADD that to current date 13/3/2017 13:30 + 4 days and 1 hour = 17/3/2017 14:30
i know how to get the diference in days hours and minutes , i cant get the second part of adding the result to the current date
any ideas?
thank you in dvance
Use Calendar class to add days and hours
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
cal.add(Calendar.DAY_OF_MONTH, yourDays); //adds days to your date
cal.add(Calendar.HOUR_OF_DAY, yourHours); //adds hours to your date
cal.getTime(); //to get Date instance
To decrement dates just add negative number, for example:
int yourDays = -daysVariable;
int yourHours = -hoursVariable; //
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
cal.add(Calendar.DAY_OF_MONTH, yourDays); //decrement days
cal.add(Calendar.HOUR_OF_DAY, yourHours); //decrement hours
cal.getTime(); //to get Date instance
Get a date object using the simpledate format
Because it is an object of the same type
Comparison is possible
I think you need to use getTime and add days throught miliseconds.
For example, if you can get the difference of days you should use something like this
date1.getTime() + 24*60*60*1000*4
(where 4 is the difference you want to add)
You can use Calendar too.
Thank you all for your ultra fast replies!
I solved it by using Mij Solution
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
cal.add(Calendar.DAY_OF_MONTH, yourDays); //adds days to your date
cal.add(Calendar.HOUR_OF_DAY, yourHours); //adds hours to your date
cal.getTime(); //to get Date instance
To add days and
tis code to decrese days
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
cal.add(Calendar.DAY_OF_MONTH, -yourDays); //adds days to your date
cal.add(Calendar.HOUR_OF_DAY, -yourHours); //adds hours to your date
cal.getTime(); //to get Date instance
and to control if date is bigget than my current date i used this condition
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (new Date().after(strDate)) {
catalog_outdated = 1;
}
it returns -1 if the date is past from current
+1 if date is bigger that current or whatever
and 0 if dates are equal
again thank you!

Subtract 6 hours from an existing Date object java (midnight corner case)

I'll be using the Calendar api for this. My primary concern is that
Date birthDate = (...say Apr 20th 0300hrs)
Calendar cal = Calendar.getInstance();
cal.setTime(birthDate);
cal.add(Calendar.HOUR, -6);
Date newDate = cal.getTime();
Will newDate be Apr 19th 2100hrs (9 PM) ?
No.
After running the following code:
Date birthDate = (...say Apr 20th 0300hrs)
Calendar cal = Calendar.getInstance();
cal.setTime(birthDate);
cal.add(Calendar.HOUR, -6);
you are guaranteed that cal is set to six hours before 'Apr 20th 0300hrs', but not that it is set to 'Apr 19th 2100hrs'.
Yes.
Reference for calendar.add
http://www.tutorialspoint.com/java/util/calendar_add.htm
Second parameter in Calendar's .add method is indeed the delta, or the change, so yes, this would subtract 6 hours.
read more here:
enter link description here

Fetching the first date of a week in java [duplicate]

This question already has answers here:
How to get the first day of the current week and month?
(15 answers)
Closed 6 years ago.
I would like to fetch the first date of a week.
My input is going to be a String type like 07/26/2014".
I need to get the first date of week in which the above date(07/26/2014) falls.
I need output date in MM/dd/YYYY format .
basically I need output as 07/21/2014.
Please give me the java program. I have done upto this
SimpleDateFormat formatter1 = new SimpleDateFormat("MM/dd/yy");
String date ="07/26/2014";
Date Currentdate = formatter1.parse(date);
int currentday=Currentdate.getDay();
Calendar calendar = Calendar.getInstance();
calendar.setTime(Currentdate);
int startDay=currentday-calendar.getFirstDayOfWeek();
Currentdate.setDate(contacteddate.getDate()-startDay);
System.out.println(contacteddate.getDate());
}
The above code only gives me the date.. I need date along with month and year in "MM/dd/YYYY"
Please help
I would do it this way
Calendar calendar = Calendar.getInstance();
calendar.setTime(Currentdate);
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
After setting time to Calendar
Calendar calendar = Calendar.getInstance();
calendar.setTime(Currentdate);
use
calendar.set(Calendar.DAY_OF_WEEK, 1)
and then
simpleFormat.format(calendar.getTime());
This will help you.
// Get calendar set to current date and time
Calendar c = Calendar.getInstance();
// Set the calendar to monday of the current week
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy");
for (int i = 0; i < 1; i++) {
System.out.println(df.format(c.getTime()));
c.add(Calendar.DATE, 1);
}
The problem with all presented solutions so far is not to specify what exactly the week definition is. Week definitions are either technically specified like in ISO-8601-standard (Monday as first day of week and first calendar week of year containing at least four days), or they use localized rules (for example in US a week begins by Sunday!).
Due to the requirement that the OP wants "07/21/2014" as first day of week around "07/26/2014" it seems that ISO-8601 is what the OP really wants. But code like
Calendar calendar = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
...
will not work in a country like US or an application server located in US. Counter example:
// simulating a US-located application server where this code is running
GregorianCalendar calendar = new GregorianCalendar(Locale.US);
calendar.set(2014, Calendar.JULY, 26);
calendar.getTime(); // avoid ugly side effects in calendar date handling
calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(sdf.format(calendar.getTime())); // output: 2014-07-20
If the OP changes the choosen locale to let's say Locale.FRANCE (applying ISO-rules) then the OP can achieve his goal using the traditional Java-date-and-time-library.
It should be noted however that week handling using the java.util.Calendar-stuff is often confusing and hard. For example: Without the strange getter-call (calendar.getTime()) which enforces update of internal calculation the result would be: 2014-07-06 (surely not what OP wants).
Therefore I recommend following other libraries to choose a generic approach compatible with different week definitions:
a) Java-8 (built-in library JSR-310 aka java.time):
LocalDate date = LocalDate.of(2014, 7, 26);
TemporalField dowField = WeekFields.ISO.dayOfWeek();
date = date.with(dowField, dowField.range().getMinimum());
System.out.println(date); // output: 2014-07-21
Note: Avoid code like date.with(DayOfWeek.MONDAY) because in that case the java.time-library cannot evaluate the underlying week rules which possibly deviate from ISO-8601 (here choosen: WeekFields.ISO, but it might also be WeekFields.SUNDAY_START).
b) my own library Time4J:
PlainDate date = PlainDate.of(2014, 7, 26);
date = date.with(Weekmodel.ISO.localDayOfWeek().minimized());
System.out.println(date); // output: 2014-07-21
c) If you know in advance that you only want ISO-8601-week-rules then you might also consider a simpler approach in Java-8 or instead its predecessor JodaTime:
// Java-8 applying ISO-8601-rules
LocalDate date = LocalDate.of(2014, 7, 26);
date = date.with(DayOfWeek.MONDAY);
// Joda-Time
LocalDate date = new LocalDate(2014, 7, 26);
date = date.dayOfWeek().withMinimumValue();

How to subtract an hour from current timestamp [duplicate]

This question already has answers here:
Changing Java Date one hour back
(11 answers)
Closed 9 years ago.
How to subtract an hour from current time-stamp?
Calendar c = Calendar.getInstance();
System.out.println("current: "+c.getTime());
Add -1 to the Calendar.HOUR attribute:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR, -1);
Oh! And with Joda Time, there you go:
DateTime date = DateTime.now();
DateTime dateOneHourBack = date.minusHours(1);
Although difference might not be visible here, but it's a much more simple and better API than Date and Calendar in JDK.
The answer you are looking for is
cal.add(Calendar.HOUR, -numberOfHours);
where numberOfHours is the amount you want to subtract.
You can also refer this link for more information
http://examples.javacodegeeks.com/core-java/util/calendar/add-subtract-hours-from-date-with-calendar/
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, -1);
Add -1
add(int field,int amount)
Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 1 hours from the current time of the calendar, you can achieve it by calling:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, -1);
call add() method with a negative parameter if you want to subtract and positive parameter if you want to add the hour.
for adding 2 hours,
calendar.add(Calendar.Hour,2);
for subtracting 3 hours,
calendar.add(Calendar.Hour,-3);

Calendar returning the wrong time

The time displayed is way ahead of what I expected. I'm parsing a date string and turning it into milliseconds.
year = Integer.parseInt(m1.group(1));
mo = Integer.parseInt(m1.group(2));
day = Integer.parseInt(m1.group(3));
hr = Integer.parseInt(m1.group(4));
min = Integer.parseInt(m1.group(5));
sec = Integer.parseInt(m1.group(6));
and here I set the Calendar
Calendar cal = Calendar.getInstance();
cal.set(year, mo, day, hr, min, sec);
time = cal.getTimeInMillis();
If you check out the calendar documentation here, then visit here, you'll see that January is month 0. You'll want to change your code to mo = Integer.parseInt(m1.group(2))-1;
You should probably use DateFormatter to parse the date string (rather than rolling your own).
Other than that, make sure that you have the proper time zone and understand that month number one is February (not January).

Categories