Is there any way to use Date in Java with the format YYYYWW? There is week of month but is there any way to find week of the year?
I am not quite sure about your question, but maybe you want a ISO-like week-date with year and week-of-year. If so then pay attention to the fact that there is another definition of a year, namely a year of weekdate (or other call it week-based-year). This year is in most cases the same as the standard calendar year but can differ at the begin or end of the calendar year dependent on the ISO-week-rules (monday as first day of week and first week-of-year having at least 4 days in calendar year).
If you look for this week-based-year and the ISO-week-of-year then you should use this expression:
// In France ISO-8601-week-rules are valid, so let's use this locale to choose ISO.
SimpleDateFormat sdf = new SimpleDateFormat("YYYYww", Locale.FRANCE); // big letter Y!
Otherwise you can of course just go with the other answer of #BetaRide: "yyyyww".
Standard Format
The ISO 8601 standard defines such week-of-year. You may want to review the Wikipedia articles here and here for guidance, as your format is not quite standard and is ambiguous. The standard uses a W and optionally a hyphen, such as YYYY-Www.
Joda-Time
The Joda-Time library has good support for ISO 8601 including weeks. See the ISODateTimeFormat class and its weekYearWeek method amongst others.
Note that time zone is crucial in determining a date and therefore a week. At the stroke of midnight ending Sunday in Paris means a new week in France while still "last week" in Montréal.
Example code using Joda-Time 2.5.
DateTime now = DateTime.now( DateTimeZone.forID( "America/Montreal" ) );
String output = ISODateTimeFormat.weekyearWeek().print( now );
int weekNumber = now.getWeekOfWeekyear();
When run.
now: 2014-11-03T02:30:10.124-05:00
output: 2014-W45
Avoid j.u.Date
The java.util.Date and .Calendar and SimpleDateFormat classes bundled with Java are notoriously troublesome. Avoid them. Use either Joda-Time or the new java.time package in Java 8 (inspired by Joda-Time).
You can use SimpleDateFormat to format and parse any date string.
The format you are looking for is "yyyyww".
Letter y represent Year where as be careful with - as w represents Week in year and W represents Week in month
try
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyww");
System.out.println(dateFormat.format(new Date()));
Refer this for more date-formats
yes we can use Y for week of the month and y for week of the year.
Ex: Date d =new Date();
SimpleDateFormat ft =
new SimpleDateFormat ("yyyyww");
System.out.println(ft.format(d));
can give you the current year and week.
Related
I have a small program that displays the current week from todays date, like this:
GregorianCalendar gc = new GregorianCalendar();
int day = 0;
gc.add(Calendar.DATE, day);
And then a JLabel that displays the week number:
JLabel week = new JLabel("Week " + gc.get(Calendar.WEEK_OF_YEAR));
So right now I'd like to have a JTextField where you can enter a date and the JLabel will update with the week number of that date. I'm really not sure how to do this as I'm quite new to Java. Do I need to save the input as a String? An integer? And what format would it have to be (yyyyMMdd etc)? If anyone could help me out I'd appreciate it!
Do I need to save the input as a String? An integer?
When using a JTextField, the input you get from the user is a String, since the date can contain characters like . or -, depending on the date format you choose. You can of course also use some more sophisticated input methods, where the input field already validates the date format, and returns separate values for day, month and year, but using JTextField is of course easier to start with.
And what format would it have to be (yyyyMMdd etc)?
This depends on your requirements. You can use the SimpleDateFormat class to parse any date format:
String input = "20130507";
String format = "yyyyMMdd";
SimpleDateFormat df = new SimpleDateFormat(format);
Date date = df.parse(input);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_YEAR);
But more likely you want to use the date format specific to your locale:
import java.text.DateFormat;
DateFormat defaultFormat = DateFormat.getDateInstance();
Date date = defaultFormat.parse(input);
To give the user a hint on which format to use, you need to cast the DateFormat to a SimpleDateFormat to get the pattern string:
if (defaultFormat instanceof SimpleDateFormat) {
SimpleDateFormat sdf = (SimpleDateFormat)defaultFormat;
System.out.println("Use date format like: " + sdf.toPattern());
}
The comment by #adenoyelle above reminds me: Write unit tests for your date parsing code.
Java 1.8 provides you with some new classes in package java.time:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.IsoFields;
ZonedDateTime now = ZonedDateTime.ofInstant(Instant.now(), ZoneId.systemDefault());
System.out.printf("Week %d%n", now.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR));
Most legacy calendars can easily be converted to java.time.ZonedDateTime / java.time.Instant by interoperability methods, in your particular case GregorianCalendar.toZonedDateTime().
tl;dr
YearWeek.from( // Represents week of standard ISO 8601 defined week-based-year (as opposed to a calendar year).
LocalDate.parse( "2017-01-23" ) // Represents a date-only value, without time-of-day and without time zone.
) // Returns a `YearWeek` object.
.getWeek() // Or, `.getYear()`. Both methods an integer number.
4
ISO 8601 standard week
If you want the standard ISO 8601 week, rather than a localized definition of a week, use the YearWeek class found in the ThreeTen-Extra project that adds functionality to the java.time classes built into Java 8 and later.
ISO-8601 defines the week as always starting with Monday. The first week is the week which contains the first Thursday of the calendar year. As such, the week-based-year used in this class does not align with the calendar year.
First, get today's date. The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
Or let the user specify a date by typing a string. Parsing string input of a date is covered in many other Questions and Answers. Simplest is to have the user use standard ISO 8601 format, YYYY-MM-DD such as 2017-01-23.
LocalDate ld = LocalDate.parse( "2017-01-23" ) ;
For other formats, specify a DateTimeFormatter for parsing. Search Stack Overflow for many many examples of using that class.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "d/M/uuuu" , Locale.US ) ;
LocalDate ld = LocalDate.parse( "1/23/2017" , f ) ;
Get the YearWeek.
YearWeek yw = YearWeek.from( ld ) ;
To create a string, consider using the standard ISO 8601 format for year-week, yyyy-Www such as 2017-W45. Or you can extract each number.
YearWeek::getWeek – Gets the week-of-week-based-year field.
YearWeek::getYear – Gets the week-based-year field.
Other definitions of week
The above discussion assumes you go by the ISO 8601 definition of weeks and week-numbering. If instead you want an alternate definition of week and week-numbering, see the Answer by Mobolaji D. using a locale’s definition.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
WeekFields
This method that I created works for me in Java 8 and later, using WeekFields, DateTimeFormatter, LocalDate, and TemporalField.
Don't forget to format your date properly based on your use case!
public int getWeekNum(String input) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/dd/yy"); // Define formatting pattern to match your input string.
LocalDate date = LocalDate.parse(input, formatter); // Parse string into a `LocalDate` object.
WeekFields wf = WeekFields.of(Locale.getDefault()) ; // Use week fields appropriate to your locale. People in different places define a week and week-number differently, such as starting on a Monday or a Sunday, and so on.
TemporalField weekNum = wf.weekOfWeekBasedYear(); // Represent the idea of this locale’s definition of week number as a `TemporalField`.
int week = Integer.parseInt(String.format("%02d",date.get(weekNum))); // Using that locale’s definition of week number, determine the week-number for this particular `LocalDate` value.
return week;
}
You can store the date as a String, and the user can enter it in pretty much any format you specify. You just need to use a DateFormat object to interpret the date that they enter. For example, see the top answer on Convert String to Calendar Object in Java.
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
cal.setTime(sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));
To read the date from a JTextField, you could replace that with something like:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // or any other date format
cal.setTime(sdf.parse(dateTextField.getText()));
Then you just need to read the week number from cal in the same way you showed in the question. (This is a simplified example. You'd need to handle the potential ParseException thrown by the DateFormat parse method.)
You can use that, but you have to parse the date value to proper date format using SimpleDateFormatter of java API. You can specify any format you want. After that you can do you manipulation to get the week of the year.
public static int getWeek() {
return Calendar.getInstance().get(Calendar.WEEK_OF_YEAR);
}
Works fine and return week for current realtime
this one worked for me
public void sortListItems(List<PostModel> list) {
Collections.sort(list, new Comparator<PostModel>() {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
#Override
public int compare(PostModel o1, PostModel o2) {
int ret = 0;
try {
ret = dateFormat.parse(o1.getDate()).compareTo(dateFormat.parse(o2.getDate()));
return ret;
} catch (ParseException e) {
e.printStackTrace();
}
return ret;
}
});
}
How can I convert time from unix timestamp to week day? For example, I want to convert 1493193408 to Wednesday.
I tryed code above, but It always shows Sunday..
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date dateFormat = new java.util.Date(1493193408);
String weekday = sdf.format(dateFormat );
Using java.time
The other Answers use the troublesome old date-time classes, now legacy, supplanted by the java.time classes.
Time zone is crucial in determining a date, and therefore getting a day-of-week.
Get an Instant from your count of while seconds since the epoch of 1970 in UTC. Apply a time zone to get a ZonedDateTime. From there extract a DayOfWeek enumerate object. Ask that object to automatically localize to generate a string of its name.
Instant.ofEpochSecond( 1_493_193_408L )
.atZone( ZoneId.of( "America/Montreal" ))
.getDayOfWeek()
.getDisplayName( TextStyle.FULL , Locale.US )
For Android, see the ThreeTenABP project for a back-port of most of the java.time functionality.
You need to multiply it by 1000 since Java and Unix time are not the same.
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date dateFormat = new java.util.Date(1493193408L * 1000);
String weekday = sdf.format(dateFormat );
You can use a calendar instance because it provides you methods for getting that information:
Date date = new Date(1493193408000L);
Calendar c = Calendar.getInstance();
c.setTime(date);
System.out.println(c.get(Calendar.DAY_OF_WEEK));
System.out.println(c.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US));
The Date constructor has the following description:
Allocates a Date object and initializes it to represent the specified
number of milliseconds since the standard base time known as "the
epoch", namely January 1, 1970, 00:00:00 GMT.
Your timestamp is in seconds, if you multiply by 1000 (to get milliseconds) you get the expected answer:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date dateFormat = new java.util.Date(1493193408000L);
System.out.println(dateFormat);
String weekday = sdf.format(dateFormat);
System.out.println(weekday);
Which prints
Wed Apr 26 09:56:48 CEST 2017
Wednesday
dateFormatStart != dateFormat
You could also check using:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date dateFormat = new Date(System.currentTimeMillis());
String weekday = sdf.format(dateFormat);
Here is right code for you:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date dateFormat = new java.util.Date(1493193408 * 1000);
String weekday = sdf.format(dateFormat );
There is documentation for Java date
You can do the same with the new JDK 8 date time classes. Local date and time is calculated using the seconds from Unix Epoch and then it can be formatted with a specific pattern. The conversion to date time takes into account the Zone as well, I have used the default Zone, but it can be modified to use a specific zone.
ZonedDateTime ldt = ZonedDateTime.ofInstant(Instant.ofEpochSecond(1493193408), ZoneId.systemDefault());
System.out.println(ldt.format(DateTimeFormatter.ofPattern("EEEE")));
It’s been said already: your problem is your are feeding number seconds since the Unix epoch into a Date when it expects the number of milliseconds (then one would have expected multiplying by 1000 to be simple, but a couple of the other answers got that part wrong).
If you are going to work with dates, times or weekdays in your app, I agree with the answers that recommend that you consider the newer classes in java.time. They are much nicer to work with. Your code will more directly express your intent.
But if you only need the weekday, a dependency on a third party library may be overkill. I still recommend keeping a distance to the oldfashioned classes SimpleDateFormat, Date and Calendar, though. Is there a third option? There certainly is! A simple oneliner, even:
String weekday = String.format(Locale.ENGLISH, "%tA", 1493193408 * 1000L);
This yields Wednesday as desired. You must still be aware that the result depends on your computer’s time zone setting, though.
Why this code
DateTimeFormatter SENT_DATE_FORMATTER = DateTimeFormatter.ofPattern("E, d MMM YYYY HH:mm:ss Z", Locale.US);
ZonedDateTime now = ZonedDateTime.now();
String dateStr = now.format(SENT_DATE_FORMATTER);
System.out.println(dateStr);
ZonedDateTime zoned = ZonedDateTime.parse(dateStr, SENT_DATE_FORMATTER);
Prints the correct date on the sysout line but throws a DateTimeParseException (Unable to obtain ZonedDateTime from TemporalAccessor) on the parse line?
Capitalized Y stands for week-based-year, see javadoc. In order to make the parser working you rather need to change it to year (u) or year-of-era (y). Then the parser can create a date out of calendar year, month (M) and day-of-month (d). Keep in mind that the week-based-year can relate to previous or next calendar year, not the actual one if your month and day-of-month are near the start or end of calendar year. Therefore it is not possible to just equalize the week-based-year to the calendar year! And without a precisely defined calendar year it is not possible to form a date.
Otherwise, if you had the week-of-week-based-year (w) in your pattern, too, then your parser would be able to understand the input because week-based-year (Y), week-of-week-based-year (w) and day-of-week (E) would also make an interpretable combination for a date.
Note however, that all given details in the input matching your pattern must be consistent (for example 2015-08-31 is Monday and not Tuesday) otherwise the parser will complain again (at least in strict mode).
I have a small program that displays the current week from todays date, like this:
GregorianCalendar gc = new GregorianCalendar();
int day = 0;
gc.add(Calendar.DATE, day);
And then a JLabel that displays the week number:
JLabel week = new JLabel("Week " + gc.get(Calendar.WEEK_OF_YEAR));
So right now I'd like to have a JTextField where you can enter a date and the JLabel will update with the week number of that date. I'm really not sure how to do this as I'm quite new to Java. Do I need to save the input as a String? An integer? And what format would it have to be (yyyyMMdd etc)? If anyone could help me out I'd appreciate it!
Do I need to save the input as a String? An integer?
When using a JTextField, the input you get from the user is a String, since the date can contain characters like . or -, depending on the date format you choose. You can of course also use some more sophisticated input methods, where the input field already validates the date format, and returns separate values for day, month and year, but using JTextField is of course easier to start with.
And what format would it have to be (yyyyMMdd etc)?
This depends on your requirements. You can use the SimpleDateFormat class to parse any date format:
String input = "20130507";
String format = "yyyyMMdd";
SimpleDateFormat df = new SimpleDateFormat(format);
Date date = df.parse(input);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_YEAR);
But more likely you want to use the date format specific to your locale:
import java.text.DateFormat;
DateFormat defaultFormat = DateFormat.getDateInstance();
Date date = defaultFormat.parse(input);
To give the user a hint on which format to use, you need to cast the DateFormat to a SimpleDateFormat to get the pattern string:
if (defaultFormat instanceof SimpleDateFormat) {
SimpleDateFormat sdf = (SimpleDateFormat)defaultFormat;
System.out.println("Use date format like: " + sdf.toPattern());
}
The comment by #adenoyelle above reminds me: Write unit tests for your date parsing code.
Java 1.8 provides you with some new classes in package java.time:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.IsoFields;
ZonedDateTime now = ZonedDateTime.ofInstant(Instant.now(), ZoneId.systemDefault());
System.out.printf("Week %d%n", now.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR));
Most legacy calendars can easily be converted to java.time.ZonedDateTime / java.time.Instant by interoperability methods, in your particular case GregorianCalendar.toZonedDateTime().
tl;dr
YearWeek.from( // Represents week of standard ISO 8601 defined week-based-year (as opposed to a calendar year).
LocalDate.parse( "2017-01-23" ) // Represents a date-only value, without time-of-day and without time zone.
) // Returns a `YearWeek` object.
.getWeek() // Or, `.getYear()`. Both methods an integer number.
4
ISO 8601 standard week
If you want the standard ISO 8601 week, rather than a localized definition of a week, use the YearWeek class found in the ThreeTen-Extra project that adds functionality to the java.time classes built into Java 8 and later.
ISO-8601 defines the week as always starting with Monday. The first week is the week which contains the first Thursday of the calendar year. As such, the week-based-year used in this class does not align with the calendar year.
First, get today's date. The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
Or let the user specify a date by typing a string. Parsing string input of a date is covered in many other Questions and Answers. Simplest is to have the user use standard ISO 8601 format, YYYY-MM-DD such as 2017-01-23.
LocalDate ld = LocalDate.parse( "2017-01-23" ) ;
For other formats, specify a DateTimeFormatter for parsing. Search Stack Overflow for many many examples of using that class.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "d/M/uuuu" , Locale.US ) ;
LocalDate ld = LocalDate.parse( "1/23/2017" , f ) ;
Get the YearWeek.
YearWeek yw = YearWeek.from( ld ) ;
To create a string, consider using the standard ISO 8601 format for year-week, yyyy-Www such as 2017-W45. Or you can extract each number.
YearWeek::getWeek – Gets the week-of-week-based-year field.
YearWeek::getYear – Gets the week-based-year field.
Other definitions of week
The above discussion assumes you go by the ISO 8601 definition of weeks and week-numbering. If instead you want an alternate definition of week and week-numbering, see the Answer by Mobolaji D. using a locale’s definition.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
WeekFields
This method that I created works for me in Java 8 and later, using WeekFields, DateTimeFormatter, LocalDate, and TemporalField.
Don't forget to format your date properly based on your use case!
public int getWeekNum(String input) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/dd/yy"); // Define formatting pattern to match your input string.
LocalDate date = LocalDate.parse(input, formatter); // Parse string into a `LocalDate` object.
WeekFields wf = WeekFields.of(Locale.getDefault()) ; // Use week fields appropriate to your locale. People in different places define a week and week-number differently, such as starting on a Monday or a Sunday, and so on.
TemporalField weekNum = wf.weekOfWeekBasedYear(); // Represent the idea of this locale’s definition of week number as a `TemporalField`.
int week = Integer.parseInt(String.format("%02d",date.get(weekNum))); // Using that locale’s definition of week number, determine the week-number for this particular `LocalDate` value.
return week;
}
You can store the date as a String, and the user can enter it in pretty much any format you specify. You just need to use a DateFormat object to interpret the date that they enter. For example, see the top answer on Convert String to Calendar Object in Java.
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
cal.setTime(sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));
To read the date from a JTextField, you could replace that with something like:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // or any other date format
cal.setTime(sdf.parse(dateTextField.getText()));
Then you just need to read the week number from cal in the same way you showed in the question. (This is a simplified example. You'd need to handle the potential ParseException thrown by the DateFormat parse method.)
You can use that, but you have to parse the date value to proper date format using SimpleDateFormatter of java API. You can specify any format you want. After that you can do you manipulation to get the week of the year.
public static int getWeek() {
return Calendar.getInstance().get(Calendar.WEEK_OF_YEAR);
}
Works fine and return week for current realtime
this one worked for me
public void sortListItems(List<PostModel> list) {
Collections.sort(list, new Comparator<PostModel>() {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
#Override
public int compare(PostModel o1, PostModel o2) {
int ret = 0;
try {
ret = dateFormat.parse(o1.getDate()).compareTo(dateFormat.parse(o2.getDate()));
return ret;
} catch (ParseException e) {
e.printStackTrace();
}
return ret;
}
});
}
I try to get the date of yesterday. So I write the next function:
public String getYestrday() {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
return dateFormat.format(date.getDate() - 1);
}
But it gives me the next warning:
The method getDate() from the type Date is deprecated
and it doesn't do it work.
Thank you for your help.
Date#getDate() is a deprecated method after JDK 1.1. You should be using Calendar class instead to manipulate dates.
From API:
Prior to JDK 1.1, the class Date had two additional functions. It
allowed the interpretation of dates as year, month, day, hour, minute,
and second values. It also allowed the formatting and parsing of date
strings. Unfortunately, the API for these functions was not amenable
to internationalization. As of JDK 1.1, the Calendar class should be
used to convert between dates and time fields and the DateFormat class
should be used to format and parse date strings. The corresponding
methods in Date are deprecated.
It is also clearly documented in the API using Date#getDate() to use Calendar#get(Calendar.DATE);
Deprecated. As of JDK version 1.1, replaced by
Calendar.get(Calendar.DAY_OF_MONTH)
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
return dateFormat.format(cal.getTime());
Use java.util.Calendar to do it. Or try JODA.
you can use Calendar class to do the same task:
Calendar c = new Calendar();
//c.add(Calendar.DAY_OF_MONTH, -1);
Date d = c.getTime();
Avoid java.util.Date & .Calendar
The accepted answer is correct. However, the java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Use either Joda-Time or the new java.time package (in Java 8).
Separate Date-Time Manipulation From Formatting
Also, the code in the question mixes date-time work with formatting. Separate those tasks to make your code clear and testing/debugging easier.
Time Zone
Time zone is critical in date-time work. If you ignore the issue, the JVM's default time zone will be applied. A better practice is to always specify rather than rely on default. Even when you want the default, explicitly call getDefault.
The beginning of the day is defined by the time zone. A new day dawns earlier in Paris than in Montréal. So if by "yesterday" you mean the first moment of that day, then you should (a) specify a time zone, and (b) call withTimeAtStartOfDay.
Joda-Time
Example code in Joda-Time 2.3.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime today = DateTime.now( timeZone );
Or convert from a java.util.Date object.
DateTime today = new DateTime( myJUDate, timeZone );
Subtract a day to get to yesterday (or day before).
DateTime yesterday = today.minusDays( 1 );
DateTime yesterdayStartOfDay = today.minusDays( 1 ).withTimeAtStartOfDay();
By default, Joda-Time and java.time parse/generate strings in ISO 8601 format.
String output = yesterdayStartOfDay.toString(); // Uses ISO 8601 format by default.
Use a formatter for a full date as four digit year, two digit month of year, and two digit day of month (yyyy-MM-dd). Such a formatter is already defined in Joda-Time.
String outputDatePortion = ISODateFormat.date().print( yesterdayStartOfDay );
Following works for me
int date = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);