In Android, I am using java.util.Calendar to get yesterday date in format yyyy-MM-dd'T'hh:mm:ss'Z'. For example if today is 31 May 2017, I want to get yesterday date as 2017-05-30T00:00:00Z.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
// Date End = yesterday
calendar.add(Calendar.DATE, -1);
Date dateEnd = calendar.getTime();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
this.dateEndStr = formatter.format(dateEnd);
I am expecting output to be 2017-05-30T00:00:00Z. But it gives me 2017-05-30T12:00:00Z.
What is wrong here? Is it TimeZone related? My timezone is GMT/UTC + 08:00 hour.
I am probably answering more than you asked about, but now you have asked, why not take all of it? I see two or three things wrong with your code. bowmore in another answer has touched on all three already, but I think a couple of them can be made a little clearer still:
Yes, the first and most serious is time zone related. You need to decide, and you should make explicit in your code, which time zone you use. And it is incorrect to give Z as time zone on a time at zone offset +08:00. Z is for Zulu time, another name for UTC.
In your format pattern, you should use capital HH for hour of day.
You should prefer the modern date and time classes, in principle always, but at least for a case like this. With these you won’t be able to make the errors you did with the oldfashioned SimpleDateFormat.
Time zone
Time zone is crucial to your task. You need to decide whether yesterday’s date in UTC (as your requested output says), in GMT/UTC + 08:00 or, say, in the the JVM’s current time zone (which can be changed at any time while your program is running). This snippet uses UTC:
this.yesterdayAtStartOfDay = LocalDate.now(ZoneOffset.UTC)
.minusDays(1)
.atStartOfDay(ZoneOffset.UTC)
.format(DateTimeFormatter.ISO_INSTANT);
Running it just now, the result is
2017-05-30T00:00:00Z
Instead of the last line of the snippet, you may use the even simpler:
.toString();
This gives the same result because atStartOfDay() gives a ZonedDateTime with time zone Z, and its toString() method gives the ISO 8601 string you requested.
If you want yesterday’s date in another time zone, in the first line of the snippet (and only the first line) use for example ZoneOffset.ofHours(8), ZoneId.of("Asia/Hong_Kong") or ZoneId.systemDefault() as time zone.
In case you are using Java 6 or 7, to use the modern date and time classes you need to get the ThreeTen-Backport library. Even though I always think twice before introducing an external dependency, I recommend this one warmly for your task.
That back-port is further adapted for Android in the ThreeTenABP project.
This is simply a mistake in your SimpleDateFormat.
You use hh for the hours, but that shows the one based hour of AM/PM.
These are the relevant symbols (from SimpleDateFormat)
H Hour in day (0-23)
k Hour in day (1-24)
K Hour in am/pm (0-11)
h Hour in am/pm (1-12)
You want this : "yyyy-MM-dd'T'HH:mm:ss'Z'"
Remark
You say your timezone is +08:00 hours, and you calculate the date using that timezone, however you format it as if it's in the Zulu timezone (which has an offset of +00:00)
BONUS
In Java 8 all this Calendar manipulating goes away :
ZonedDateTime yesterday = ZonedDateTime.now().with(ChronoField.NANO_OF_DAY, 0).minusDays(1);
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
dateEndStr = formatter.format(dateEnd);
cal.add(Calendar.DAY_OF_YEAR, -1);
To subtract days, you should use:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, -5);
Related
I have a report created in Jasper Reports which ONLY recognizes java.util.Date's (not Calendar or Gregorian, etc).
Is there a way to create a date 7 days prior to the current date?
Ideally, it would look something like this:
new Date(New Date() - 7)
UPDATE: I can't emphasize this enough: JasperReports DOES NOT RECOGNIZE Java Calendar objects.
From exactly now:
long DAY_IN_MS = 1000 * 60 * 60 * 24;
new Date(System.currentTimeMillis() - (7 * DAY_IN_MS))
From arbitrary Date date:
new Date(date.getTime() - (7 * DAY_IN_MS))
Edit: As pointed out in the other answers, does not account for daylight savings time, if that's a factor.
Just to clarify that limitation I was talking about:
For people affected by daylight savings time, if by 7 days earlier, you mean that if right now is 12pm noon on 14 Mar 2010, you want the calculation of 7 days earlier to result in 12pm on 7 Mar 2010, then be careful.
This solution finds the date/time exactly 24 hours * 7 days= 168 hours earlier.
However, some people are surprised when this solution finds that, for example, (14 Mar 2010 1:00pm) - 7 * DAY_IN_MS may return a result in(7 Mar 2010 12:00pm) where the wall-clock time in your timezone isn't the same between the 2 date/times (1pm vs 12pm). This is due to daylight savings time starting or ending that night and the "wall-clock time" losing or gaining an hour.
If DST isn't a factor for you or if you really do want (168 hours) exactly (regardless of the shift in wall-clock time), then this solution works fine.
Otherwise, you may need to compensate for when your 7 days earlier doesn't really mean exactly 168 hours (due to DST starting or ending within that timeframe).
Use Calendar's facility to create new Date objects using getTime():
import java.util.GregorianCalendar;
import java.util.Date;
Calendar cal = new GregorianCalendar();
cal.add(Calendar.DAY_OF_MONTH, -7);
Date sevenDaysAgo = cal.getTime();
try
Date sevenDay = new Date(System.currentTimeMillis() - 7L * 24 * 3600 * 1000));
Another way is to use Calendar but I don't like using it myself.
Since no one has mentioned TimeUnit yet:
new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7))
Java 8 based solution:
new Date(
Instant.now().minus(7, ChronoUnit.DAYS)
.toEpochMilli()
)
Try this:
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_MONTH, -7);
return c.getTime();
A determining "days" requires a time zone. A time zone defines when a "day" begins. A time zone includes rules for handling Daylight Saving Time and other anomalies. There is no magic to make time zones irrelevant. If you ignore the issue, the JVM's default time zone will be applied. This tends to lead to confusion and pain.
Avoid java.util.Date
The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. They are so bad that Sun/Oracle agreed to supplant them with the new java.time package in Java 8. Use either that or Joda-Time.
Joda-Time
Example code in Joda-Time 2.3.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" ); // Specify or else the JVM's default will apply.
DateTime dateTime = new DateTime( new java.util.Date(), timeZone ); // Simulate passing a Date.
DateTime weekAgo = dateTime.minusDays( 7 );
First Moment Of Day
Or, you may want to adjust the time-of-day to the first moment of the day so as to capture an entire day's worth of time. Call the method withTimeAtStartOfDay. Keep in mind this is usually 00:00:00 but not always.
Avoid the "midnight" methods and classes in Joda-Time. They are based on a faulty concept and are now deprecated.
DateTime dateTimeStart = new DateTime( new java.util.Date(), timeZone ).withTimeAtStartOfDay(); // Not necessarily the time "00:00:00".
DateTime weekAgo = dateTime.minusDays( 7 ).withTimeAtStartOfDay();
Convert To/From j.u.Date
As seen above, to convert from java.util.Date to Joda-Time merely pass the Date object to constructor of DateTime. Understand that a j.u.Date has no time zone, a DateTime does. So assign the desired/appropriate time zone for deciding what "days" are and when they start.
To go the other way, DateTime to j.u.Date, simply call the toDate method.
java.util.Date date = dateTime.toDate();
I'm not sure when they added these, but JasperReports has their own set of "functions" that can manipulate dates. Here is an example that I haven't tested thoroughly:
DATE(YEAR(TODAY()), MONTH(TODAY()), DAY(TODAY()) - 7)
That builds a java.util.Date with the date set to 7 days from today. If you want to use a different "anchor" date, just replace TODAY() with whatever date you want to use.
You can try this,
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_MONTH, -7);
System.out.println(new java.sql.Date(c.getTimeInMillis()));
Due to the heated discussion:
The question may not have a proper answer w/o a designated timezone.
below it is some code to work w/ the default (and hence deprecated) timezone that takes into account the default timezone daylight saving.
Date date= new Date();
date.setDate(date.getDate()-7);//date works as calendar w/ negatives
While the solution does work, it is exactly as bogus as in terms of assuming the timezone.
new Date(System.currentTimeMillis() - 10080*60000);//a week has 10080 minutes
Please, don't vote for the answer.
I'm doing it this way :
Date oneWeekAgo = DateUtils.addDays(DateUtils.truncate(new Date(), java.util.Calendar.DAY_OF_MONTH), -7);
I am trying to get the current time in 24 hours format by using the code below:
Calendar cal = Calendar.getInstance();
int currentHour = cal.get(Calendar.HOUR);
int currentMinute = cal.get(Calendar.MINUTE);
System.out.println(currentHour);
System.out.println(currentMinute);
My current time is 3.11PM Singapore time. But then when I execute the code above, I am getting 7.09. Any ideas?
I figured the solution already:
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("GMT+8"));
currentHour = cal.get(Calendar.HOUR_OF_DAY);
currentMinute = cal.get(Calendar.MINUTE);
The code above returns exactly what I wanted
This will give you the time in 24 hr format
public String getFormattedTime() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormatter = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
return dateFormatter.format(calendar.getTime());
}
I can’t be sure from the information you have provided, but the likely cause is that your JVM’s time zone setting is UTC. If you ran your program at, say, 15:09:55 Singapore time, that would print as 7 and 9 in UTC. If you then read your clock in Singapore time a little over a minute later, or read it from a clock that wasn’t in perfect synch with your device (or simulator), it would show 3:11 PM.
The JVM usually picks up its time zone setting from the device, but there can be all sorts of reasons why it is getting it from somewhere else.
As Anton A. said in a comment, you need HOUR_OF_DAY instead of HOUR for 24 hour format (though the time was 7:09 AM in UTC, so this error wasn’t the cause of the unexpected hour in your case).
java.time
The modern way to print the current time is:
System.out.println(LocalTime.now(ZoneId.of("Asia/Singapore")));
The Calendar class that you were using is long outdated and poorly designed. LocalTime is the class from java.time, the modern Java date and time API, that represents the time of day (without time zone, but the now method accepts a time zone to initialize to the current time in that zone). If your Android device is less than new (under API level 26), you will need the ThreeTenABP library in order to use it. See How to use ThreeTenABP in Android Project.
One more link: Oracle tutorial: Date Time explaining how to use java.time.
If I take current date from my application, it comes with variation like below:
scenario 1: when the date is less than 10th of the month, a month is less than 10 of the year --> example: 5/9/18
scenario 2: when the date is >= 10th of the month, a month is less >= 10 of the year --> example: 10/11/18
Note: all the examples are in MM/DD/YY format and timezone is the USA
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy HH:mm a");
String PastDate = dateFormat.format(cal.getTime());
info("Date is displayed as : "+ PastDate );
The above piece of code throwing me an error when the scenario 1 is in place. But if I format the date-time as "M/d/yy H:mm a" it works for both the scenario. I need the date add also.
Will it be a good practice to use the 2nd format? or there is any other way to get it done. Expert guidance please..
java.time
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
.withLocale(Locale.US);
ZonedDateTime dayBeforeYesterday = ZonedDateTime.now(ZoneId.of("America/St_Thomas"))
.minusDays(2);
System.out.println(dayBeforeYesterday.format(formatter));
Running just now I got this output:
5/7/18, 8:44 AM
Please specify your desired time zone where I put America/St_Thomas. Think twice before you use ZoneId.systemDefault() for your JVM’s time zone setting since this setting may be changed at any time from other parts of your program or other programs running in the same JVM; but if you trust the setting reflects the user’s time zone, it’s the correct thing to use.
Rather than defining your own output format prefer using one of the built-in formats you get from DateTimeFormatter.ofLocalizedDateTime. Do specify locale (no matter if you use a built-in format or roll your own). Again, use Locale.getDefault() if you trust the JVM’s setting is correct.
Avoid the old date and time classes like Calendar, DateFormat and SimpleDateFormat. They are not only long outdated, they are also poorly designed and the last two in particular notoriously troublesome. Today we have so much better in java.time, the modern Java date and time API.
Link: Oracle tutorial: Date Time explaining how to use java.time.
The number of characters in the format MM indicates that two digits are required in the input. A single character M will match one or two digits. Use M/d/yy H:mm a to support your desired formats.
I have a date in the string that looks like MON 07:15. I'm trying to parse this to a Date using this snippet of code:
System.out.println(new SimpleDateFormat("E kk:mm").parse("MON 07:15"));
Using the above code, prints a date that reads:
Mon Jan 05 07:15:00 EET 1970
I'd like the parse the date string to the next upcoming date. At the time of posting, my local date and time is Fri Aug 08 11:45:00 EEST 2014 and the next Monday will be on the 11th so the resultant date that I'm looking for is Mon Aug 11 07:15:00 EEST 2014. How can I parse this?
The day and time object that I'll be parsing will always be in the future.
I would separate parsing from everything else.
Parse the value as you're already doing, which gives you a date in the wrong year.
From that, take the time of day and the day of week - those are the important things. You can throw everything else away.
Next, take the current date and time, and perform whatever operations you need to in order to get to the right date/time. You should consider:
What time zone are you interested in?
If the current time is 06:00 on a Monday and you've been asked for 07:15 on a Monday, does that mean today or next Monday?
If the current time is 08:00 on a Monday and you've been asked for 07:15 on a Monday, does that mean today or next Monday?
By separating out the parsing from the computations, you can make the testing simpler two: test each of the operations separately. I'd advise using a clock abstraction of some kind to indicate "an object which can get you the current instant in time" - that way you can test all kinds of combinations of "desired day/time" and "current day/time".
Ideally, use java.time from Java 8 or Joda Time - both are much nicer than the java.util.* API.
Are you looking something like following?
DateFormat df = new SimpleDateFormat("E kk:mm");
Date date = df.parse("MON 07:15");
Date today = new Date();
Calendar calendar = Calendar.getInstance();
Calendar calendar1 = Calendar.getInstance();
calendar.setTime(today);
calendar1.setTime(date);
if (calendar.get(Calendar.DAY_OF_WEEK) == calendar1.get(Calendar.DAY_OF_WEEK)) {
String time = df.format(today);
Date t1 = df.parse(time);
if (t1.before(date)) {
calendar.set(Calendar.HOUR, calendar1.get(Calendar.HOUR));
calendar.set(Calendar.MINUTE, calendar1.get(Calendar.MINUTE));
calendar.set(Calendar.SECOND, 0);
System.out.println(calendar.getTime());
} else {
calendar.add(Calendar.DATE, 7);
calendar.set(Calendar.HOUR_OF_DAY, calendar1.get(Calendar.HOUR));
calendar.set(Calendar.MINUTE, calendar1.get(Calendar.MINUTE));
calendar.set(Calendar.SECOND, 0);
System.out.println(calendar.getTime());
}
} else {
int toDay = calendar.get(Calendar.DAY_OF_WEEK);
int givenDay = calendar1.get(Calendar.DAY_OF_WEEK);
int count = 7 - toDay + givenDay;
calendar.add(Calendar.DAY_OF_MONTH, count);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.HOUR_OF_DAY, calendar1.get(Calendar.HOUR));
calendar.set(Calendar.MINUTE, calendar1.get(Calendar.MINUTE));
System.out.println(calendar.getTime());
}
Out put:
Mon Aug 11 07:15:00 IST 2014
Leave me a comment telling me whether I got your question correct.
This answer addresses the second part, getting the next logical date from today.
Avoid .Date/.Calendar
The java.util.Date & .Calendar classes bundled with Java are notoriously troublesome. Avoid them.
Joda-Time or java.time
I suggest learning how to use a sophisticated date-time library. In Java that means either:
Joda-Time
java.time (built into Java 8, inspired by Joda-Time).
Time Zone
The time zone is crucial in determining the day and day-of-week. Use proper time zone names, never the 3 or 4 letter codes.
If you ignore time zone, the JVM’s current default time zone will be applied implicitly. This means different outputs when moving your app from one machine to another, or when a sys admin changes the time zone of host machine, or when any Java code in any thread of any app within the same JVM decides to call setDefault even during your app‘s execution.
Example Code To Get Next Day-Of-Week
Here is example code using Joda-Time 2.7.
Get the time zone you desire/expect. If working in UTC, use the constant DateTimeZone.UTC.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
Get the date-time value you need. Here I am using the current moment.
DateTime dateTime = DateTime.now( zone );
Specify the future day-of-week you want. Note that Joda-Time uses the sensible # 1 for first day of week, rather than zero-based counting found in java.util.Calendar. First day of week is Monday, per international norms and standards (not Sunday as is common in United States).
int dayOfWeek = DateTimeConstants.SATURDAY;
The withDayOfWeek command may go back in time. So we use a ternary operator (?:) to make sure we go forwards in time by adding a week as needed.
DateTime future = ( dateTime.getDayOfWeek() < dayOfWeek )
? dateTime.withDayOfWeek( dayOfWeek )
: dateTime.plusWeeks( 1 ).withDayOfWeek( dayOfWeek );
You may want to adjust the time-of-day to the first moment of the day to emphasize the focus on the day rather than a particular moment within the day.
future = future.withTimeAtStartOfDay(); // Adjust time-of-day to first moment of the day to stress the focus on the entire day rather than a specific moment within the day. Or use `LocalDate` class.
Dump to console.
System.out.println( "Next day # " + dayOfWeek + " after " + dateTime + " is " + future );
When run.
Next day # 6 after 2015-04-18T16:03:36.146-04:00 is 2015-04-25T00:00:00.000-04:00
I need to generate a new Date object for credit card expiration date, I only have a month and a year, how can I generate a Date based on those two? I need the easiest way possible. I was reading some other answers on here, but they all seem too sophisticated.
You could use java.util.Calendar:
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.YEAR, year);
Date date = calendar.getTime();
java.time
Using java.time framework built into Java 8
import java.time.YearMonth;
int year = 2015;
int month = 12;
YearMonth.of(year,month); // 2015-12
from String
YearMonth.parse("2015-12"); // 2015-12
with custom DateTimeFormatter
import java.time.format.DateTimeFormatter;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM yyyy");
YearMonth.parse("12 2015", formatter); // 2015-12
Conversions
To convert YearMonth to more standard date representation which is LocalDate.
LocalDate startMonth = date.atDay(1); //2015-12-01
LocalDate endMonth = date.atEndOfMonth(); //2015-12-31
Possibly a non-answer since you asked for a java.util.Date, but it seems like a good opportunity to point out that most work with dates and times and calendars in Java should probably be done with the Joda-Time library, in which case
new LocalDate(year, month, 1)
comes to mind.
Joda-Time has a number of other nice things regarding days of the month. For example if you wanted to know the first day of the current month, you can write
LocalDate firstOfThisMonth = new LocalDate().withDayOfMonth(1);
In your comment you ask about passing a string to the java.util.Date constructor, for example:
new Date("2012-09-19")
This version of the constructor is deprecated, so don't use it. You should create a date formatter and call parse. This is good advice because you will probably have year and month as integer values, and will need to make a good string, properly padded and delimited and all that, which is incredibly hard to get right in all cases. For that reason use the date formatter which knows how to take care of all that stuff perfectly.
Other earlier answers showed how to do this.
Like
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM");
Date utilDate = formatter.parse(year + "/" + month);
Copied from Create a java.util.Date Object from a Year, Month, Day Forma
or maybe like
DateTime aDate = new DateTime(year, month, 1, 0, 0, 0);
Copied from What's the Right Way to Create a Date in Java?
The most common sense approach would be to use the Date("YYYY-MM-DD") constructor even though it is deprecated. This is the easiest way to create a date on the fly. Screw whoever decided to deprecate it. Long live Date("YYYY-MM-DD")!!!
Don’t use this answer. Use the answers by Przemek and Ray Toel. As Przemek says, prefer to use a YearMonth for representing year and month. As both say, if you must use a date, use LocalDate, it’s a date without time of day.
If you absolutely indispensably need an old-fashioned java.util.Date object for a legacy API that you cannot change, here’s one easy way to get one. It may not work as desired, it may not give you exactly the date that you need, it depends on your exact requirements.
YearMonth expiration = YearMonth.of(2021, 8); // or .of(2021, Month.AUGUST);
Date oldFashionedDateObject = Date.from(expiration
.atDay(1)
.atStartOfDay(ZoneId.systemDefault())
.toInstant());
System.out.println(oldFashionedDateObject);
On my computer this prints
Sun Aug 01 00:00:00 CEST 2021
What we got is the first of the month at midnight in my local time zone — more precisely, my JVM’s time zone setting. This is one good guess at what your legacy API expects, but it is also dangerous. The JVM’s time zone setting may be changed under our feet by other parts of the program or by other programs running in the same JVM. In other words, we cannot really be sure what we get.
The time zone issue gets even worse if the date is transmitted to a computer running a different time zone, like from client to server or vice versa, or to a database running its own time zone. There’s about 50 % risk that your Date will come through as a time in the previous month.
If you know the time zone required in the end, it will help to specify for example ZoneId.of("America/New_York") instead of the system default in the above snippet.
If your API is lenient and just needs some point within the correct month, you’ll be better off giving it the 2nd of the month UTC or the 3rd of the month in your own time zone. Here’s how to do the former:
Date oldFashionedDateObject = Date.from(expiration
.atDay(2)
.atStartOfDay(ZoneOffset.UTC)
.toInstant());