This question already has answers here:
Why is January month 0 in Java Calendar?
(18 answers)
Why Java Calendar set(int year, int month, int date) not returning correct date? [duplicate]
(3 answers)
Closed 3 years ago.
Im using File.getlastmodified() to get last modifies of files but for some reason (probably UIT) its printing wrong date and month (year is fine)
Im getting last modifed with the above method and saving it to Long
//This should ideally conver the last modified to human radable format
but its returning wrong month adn date
like----> 27/11/2018
shows as---> 28/10/2018
c = Calendar.getInstance();
Long epoch = files[i].lastModified();
epoch+=32400L;
c.setTimeInMillis(epoch); //im converting the milliseconds to human readable formate
int year=c.get(Calendar.YEAR);
int month=c.get(Calendar.MONTH);
int day=c.get(Calendar.DATE);
The value is not incorrect.
You are using the Calendar incorrectly. Checking the documentation you can see the value returned for Month.
Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.
Source
Now, for the day, I would suspect the addition of 32 seconds could be the problem. But most probably the timezone. Indeed, the method return a value on GMT.
Note that I have check with a file modified the "2019-04-17 14:52:13" and get the correct result. Also, you can format the Calendar using a SimpleDateFormat instance instead of extracting the value like this.
private static String formatEpoch(long epoch) {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(epoch));
}
Or, we can never mention this enough, using a more recent API for date with Instant.
private static String formatEpoch(long epoch) {
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
return formatter.format(Instant.ofEpochMilli(epoch).atZone(ZoneId.systemDefault()));
}
An instant is a date-time at GMT, so we add the locale timezone before formatting it with a DateTimeFormatter to provide a value like :
2019-04-17T14:52:13.118
Related
This question already has answers here:
Julian day of the year in Java
(9 answers)
Closed 2 years ago.
Requirement : get the date in Julian format (ordinal date), compare it with current date, get the month and year out of it.
Convert it with output format.
Input format: yydddd
Output format: yymm
JDK 8
One way I can do is using date :
Date myDateWrong = new SimpleDateFormat("yyyyddd").parse("2020366");
Any cleaner way ?
java.time
looking for java.time.* solution which can parse yyyyddd format
That’s what I recommend too.
DateTimeFormatter dayOfYearFormatter
= DateTimeFormatter.ofPattern("uuuuDDD");
DateTimeFormatter yearMonthFormatter
= DateTimeFormatter.ofPattern("uuMM");
String yyyydddString = "2020366";
LocalDate date = LocalDate.parse(yyyydddString, dayOfYearFormatter);
String output = date.format(yearMonthFormatter);
System.out.println(output);
Output is:
2012
So year 2020 month 12.
What went wrong in your code?
Whether you use the modern DateTimeFormatter or the old and troublesome SimpleDateFormat, lowercase d is for day of month and uppercase D is for day of year. Why it worked with SimpleDateFormat anyway was because that class confusingly defaults month to January if no month is given. So your date was parsed into the 366th day of January. What?! That’s right, one more confusing trait of SimpleDateFormat, with default settings it happily parses non-existent dates. When there are only 31 days in January, it just extrapolates into the following months and ends up at December 31, the day you had intended. SimpleDateFormat is so full of nasty surprises like these. I recommend you never ever use that class again.
Link
Oracle tutorial: Date Time explaining how to use java.time.
This question already has answers here:
Adding days to a date in Java [duplicate]
(6 answers)
Closed 3 years ago.
I need to set up a program that compares the date of creation of a date object(say date object 1), with another a future date or date object(say date object 2) that represents the deadline. For example, if i create an initial datetime object, I want to be able to compare the current date of creation with lets say, a date 18 days after said date(deadline).I don't want to hardcode the actual dates and deadlines. It should return a bool( true when current date is equal or later than the deadline date, false otherwise). Eventually, I'll want to store the date of the deadline in an external database, then when appropriate compare said deadline date with the current date.
I can get the current date with the code below but unsure how to obtain a deadline day by specifyinging "x" days from the current date instead of hardcoding the date values.
I know how to create a date object(as show below) but i want to be able to create a deadline date object in correspondence to the current date of creation, store the deadline date in a database, while continually comparing the current date with the deadline date.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.now();
System.out.println(dtf.format(localDate)); //2016/11/16
To create a "non-hardcoded deadline" as you put it;
LocalDate currentDate = LocalDate.now();
LocalDate deadline = LocalDate.now().plusDays(10); // x = 10
storeDb(deadline);
Then later for deadline check;
LocalDate deadline = getDeadlineFromDb();
LocalDate currentDate = LocalDate.now();
if (currentDate.isAfter(deadline)) {
// deadline has passed
}
For more details check; Introduction to the Java 8 Date/Time API
This question already has answers here:
java date problem in parsing
(4 answers)
Closed 7 years ago.
I am getting a date by ajax in String format. But it is getting changed when I am converting it to date by SimpleDateFormat. The month is always changed to Jan. I am worried only about the month change.My code is given below
String appointmentDate = request.getParameter("appointmentDate");
System.out.println(" appointment date in String format "+appointmentDate);
Here I am getting the date correctly(16/12/2015). But when I am changing it to Date format it is getting changed(Fri Jan 16 00:12:00 IST 2015). Whatever I input the month, say August, May, June, I am always getting month Jan.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
Date parsedDate = dateFormat.parse(appointmentDate);
System.out.println(" appointment date in DATE format "+parsedDate);
Please help me out. Thanks in advance.
As per the JavaDoc, lower case m denotes minutes, not months.
Changing your expression to dd/MM/yyyy should fix the issue.
This question already has answers here:
How to check if a date Object equals yesterday?
(9 answers)
Closed 8 years ago.
I have these codes to get the date today in my server
DefaultTableModel dnow = MyDB.DataTable("SELECT date_format(now(),'%m-%d-%Y')");
and these code for the formatting for the date.
SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy");
now how can I get the date of yesterday?
should I just minus it with one?
An alternative approach is to do the math in SQL. The statement may vary depending on what database platform you're using.
DefaultTableModel dnow =
MyDB.DataTable("SELECT date_format(now() - INTERVAL 1 DAY,'%m-%d-%Y')");
No, build a Date (or better yet use joda's DateTime object) and then do your arithmetic. I will give you two solutions, one with Joda and the other without, starting with without:
Date d = format.parse(dnow.getDataVector().get(dnow.getTable().getSelectedRow()));
d.add(Calendar.DATE, -1);
Now, using joda:
DateTime d = new DateTime(format.parse(dnow.getDataVector().get(dnow.getTable().getSelectedRow()))).minusDays(1);
This should work perfect for you,
Calendar cal = Calendar.getInstance()
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date = "+ cal.getTime());
This will simply subtract 1 day from the current calendar date, providing you yesterdays date
If you store your timestamps internally as POSIX times (milliseconds since MN Jan 1, 1970) then you can add or subtract a day to any time stamp as easily as:
Date today = new Date(); // today
Date tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000)); // tomorrow
The huge bonus to POSIX time is that it is always in UTC. UTC is a global, "fixed" point of reference. Then if you need to need to have this date displayed for the user in any time zone, in any daylight savings zone, for any place that is accounted for in the Olson Time Zone database, you can simply create a Calendar:
GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("America/Chicago"));
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.setCalendar(gc);
sdf.applyPattern("MM-dd-yyyy");
// Now your formatter is set with the pattern and a time zone-aware Calendar.
// The world is at your command
String myOutput = sdf.format(tomorrow);
I highly recommend dealing with timestamps internally in your data model in some form of UTC representation. Doing date arithmetic with POSIX time (or Julian Day Numbers, or Modified Julian Day Numbers) is easy peasy, and the Java date/time API has enough capability to deal with most local time conversions without much fuss from you.
I am using SimpleDateFormat to display a Calendar like this :
public String getDate()
{
String DATE_FORMAT = "EEEE, dd/MM/yyyy HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
System.err.println(date.getTime().getMonth());
return sdf.format(date.getTime());
}
The shell returns 6 and the display : mardi, 06/07/2010 12:44:52
It can't be possible ? Why ?
Thanks
From the Java API:
public int getMonth()
Returns a number representing the month that contains or begins with the instant in time represented by this Date object. The value returned is between 0 and 11, with the value 0 representing January.
Unfortunately, months in class Date and class Calendar are zero-based. (In my opinion, this was a huge design mistake in those classes, and it's just one of the many design mistakes in Java's date and time API).
Note that class Calendar has constants to represent the months: Calendar.JANUARY, Calendar.FEBRUARY etc. Use those instead of the raw numbers.
An often mentioned, much better date and time API for Java is Joda Time. Note that there is a proposal to add a new date and time API to the next version of Java that will be based on Joda Time.
the getMonth method in Date is 0 indexed. from the JavaDoc:
Returns a number representing the month that contains or begins with the instant in time represented by this Date object. The value returned is between 0 and 11, with the value 0 representing January.
month index starts from 0 just like array index
that's your locale set to france DD/MM/YY so it is tuesday, July, 2010.
the 6th month is july if it starts at 0.