I have to parse date using the following format: "201710" where 10 - week of year number. I tried to implement it in this way:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyw");
java.time.LocalDate startDate = java.time.LocalDate.parse("201710", formatter);
System.out.println(startDate);
But it throws exception:
java.time.format.DateTimeParseException: Text '201710' could not be parsed at index 0
And after that I need to get first and last day of week from LocalDate object.
e.g "201710" - 05.03 12.03 (first day of week needs to be Sunday).
The accepted answer of #Kayaman is not correct because you cannot mix standard date representations (using yyyy = year-of-era) and week-date representations (using ww = week of week-based year). The subtile difference between a standard calendar year and a weekbased year is relevant near the start or end of a calendar year. Conclusion: Don't use the symbol "y", but rather the symbol "Y". Counter example for the input "201501":
Correct solution
DateTimeFormatter formatter =
new DateTimeFormatterBuilder()
.appendValue(WeekFields.ISO.weekBasedYear(), 4)
.appendValue(WeekFields.ISO.weekOfWeekBasedYear(), 2)
.parseDefaulting(ChronoField.DAY_OF_WEEK, 1)
.toFormatter();
LocalDate startDate = LocalDate.parse("201501", formatter);
System.out.println(startDate); // 2014-12-29
Based on the proposal of #Kayaman:
DateTimeFormatter dtf =
new DateTimeFormatterBuilder()
.appendValue(ChronoField.YEAR, 4)
.appendValue(ChronoField.ALIGNED_WEEK_OF_YEAR, 2)
.parseDefaulting(WeekFields.ISO.dayOfWeek(), 1)
.toFormatter();
System.out.println(LocalDate.parse("201501", dtf)); // 2015-01-05 (wrong)
The resulting dates are different! The difference is caused by the definition of the calendar year which always starts on first of January while a week-based year always starts on Monday (ISO-8601-definition) using the first week of calendar year which has at least 4 days.
Additional note a): Java-8 does not manage adjacent digit parsing of localizible fields like the week-based fields (see also the associated JDK issue), therefore I have chosen the builder-based solution instead of defining the pattern "YYYYww" (Java-9 promises a solution, however). But even with Java-9, a build-based approach is still necessary because of the need to define a default for the missing day-of-week (here: setting to Monday).
Additional note b): If you are looking for a true type for the combination of week-based year and week-of-year and use LocalDate just as a workaround for this missing type, well, you can find such a type in 3rd-party libraries, either in Threeten-Extra or in my library Time4J. Example:
ChronoFormatter<CalendarWeek> cf =
ChronoFormatter.ofPattern(
"YYYYww",
PatternType.CLDR,
Locale.ROOT,
CalendarWeek.chronology()
);
CalendarWeek cw = cf.parse("201501");
System.out.println(cw); // 2015-W01
System.out.println(cw.at(Weekday.MONDAY)); // 2014-12-29
The (previous) duplicate works if there's a space between the values, however without a space the following parses nicely.
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.appendValue(ChronoField.YEAR, 4)
.appendValue(ChronoField.ALIGNED_WEEK_OF_YEAR, 2)
.parseDefaulting(WeekFields.SUNDAY_START.dayOfWeek(), 1)
.toFormatter();
System.out.println(LocalDate.parse("201710", dtf));
// 2017-03-05
Replacing the SUNDAY_START with ISO will give you weeks starting with mondays (so it will print 2017-03-06).
ThreeTen-Extra
The ThreeTen-Extra project adds functionality to the java.time classes.
YearWeek
This library offers the YearWeek class that may prove useful to you. This class uses the ISO 8601 standard definition of a week.
If possible, I suggest you change your own strings to use the standard format: yyyy-Www such as 2018-W07. The standard format is used by default in the YearWeek class for generating/parsing stings.
YearWeek yw = YearWeek.parse( "2018-W07" );
But if you insist on your own non-standard format, we must define our own DateTimeFormatter to match your input. I took one line of the YearWeek.parse method from the YearWeek.java source code, and modified to fit your case by disabling two method calls.
DateTimeFormatter f =
new DateTimeFormatterBuilder()
// .parseCaseInsensitive()
.appendValue( WEEK_BASED_YEAR , 4 , 10 , SignStyle.EXCEEDS_PAD )
// .appendLiteral("-W")
.appendValue( WEEK_OF_WEEK_BASED_YEAR , 2 )
.toFormatter();
Let’s try it.
YearWeek yw = YearWeek.parse( "201807" , f );
yw.toString(): 2018-W07
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.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
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.
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 adds 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 bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). 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.
Related
Hi i am trying to get the current year in the below code however it is returning a 1970 year instead of 2020 last month this was working correctly but since we in January 2020, it is now returning a date from 1970, please assist
public String firstDateOfNextMonth(){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar today = Calendar.getInstance();
Calendar next = Calendar.getInstance();
today.clear();
Date date;
next.clear();
next.set(Calendar.YEAR, today.get(Calendar.YEAR));
next.set(Calendar.MONTH, today.get(Calendar.MONTH)+ 1);
next.set(Calendar.DAY_OF_MONTH, 1);
date = next.getTime();
Log.d(TAG, "The Date: " + dateFormat.format(date));
return dateFormat.format(date);
}
If you have Java 8 or above, then you have java.time and you won't have to rely on outdated datetime implementations and you can do it this way:
public static String getFirstOfNextMonth() {
// get a reference to today
LocalDate today = LocalDate.now();
// having today,
LocalDate firstOfNextMonth = today
// add one to the month
.withMonth(today.getMonthValue() + 1)
// and take the first day of that month
.withDayOfMonth(1);
// then return it as formatted String
return firstOfNextMonth.format(DateTimeFormatter.ISO_LOCAL_DATE);
}
which prints the following when called today (2020-01-03) like System.out.println(getFirstOfNextMonth());:
2020-02-01
You might have to involve an external library, the ThreeTenAbp if you want it to work in Android below API level 26. Its use is explained in this question.
not sure why the today date gets cleared, remove today.clear() at line 4
today.clear(); initalize all elements of a date with the value 0
removing this line will give you the right answer
tl;dr
LocalDate // Represent a date-only value without a time-of-day and without a time zone.
.now( // Determine the current date as seen through the wall-clock time used by people in certain region (a time zone).
ZoneId.of( "America/Montreal" ) // Real time zone names have names in the format of `Continent/Region`. Never use 2-4 letter pseudo-zones such as `IST`, `PST`, or `CST`, which are neither standardized nor unique.
) // Return a `LocalDate`.
.with( // Move from one date another by passing a `TemporalAdjuster` implementation.
TemporalAdjusters // Class providing several implementations of `TemporalAdjuster`.
.firstDayOfNextMonth() // This adjuster finds the date of the first of next month, as its name suggests.
) // Returns another `LocalDate` object. The original `LocalDate` object is unaltered.
.toString() // Generate text in standard ISO 8601 format of YYYY-MM-DD.
See this code run live at IdeOne.com.
2020-02-01
Details
You are using terrible date-time classes that were made obsolete years ago by the unanimous adoption of JSR 310 defining the java.time classes.
The Answer by deHaar is correct. Here is an even shorter solution.
TemporalAdjuster
To move from one date to another, the java.time classes include the TemporalAdjuster interface. Pass one of these objects to the with method found on many of the other java.time classes.
TemporalAdjusters.firstDayOfNextMonth()
Several implementations of that interface are found in the class TemporalAdjusters (note the s plural). One of those is firstDayOfNextMonth(), just what you need.
Get today's date. A time zone is required, as for any given moment the date varies around the globe by time zone. If omitted, your JVM's current default time zone is implicitly applied. Better to be explicit.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
LocalDate today = LocalDate.now( z ) ;
Get your TemporalAdjuster object.
TemporalAdjuster ta = TemporalAdjusters.firstDayOfNextMonth() ;
Apply that adjuster to get another LocalDate object. Note that java.time classes are immutable by design. So we get a new object rather than altering the original.
LocalDate firstOfNextMonth = today.with( ta ) ;
We can shorten this code to a one-liner, if desired.
LocalDate firstOfNextMonth =
LocalDate
.now(
ZoneId.of( "Africa/Tunis" )
)
.with(
TemporalAdjusters.firstDayOfNextMonth()
)
;
Text
Your desired output format of YYYY-MM-DD complies with the ISO 8601 standard used by default in the java.time classes when parsing/generating text. So no formatting pattern need be specified.
String output = firstOfNextMonth.toString() ;
2020-02-01
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.
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 adds 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 bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). 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.
You are using Calendar.clear() which clears all the fields of your calendar, and essentially reverts it to 1/1/1970 (epoch time 0).
remove today.clear() and you'll get the correct answer
see more here
Remove next.clear();. As Calendar next= Calendar.getInstance(); initiates next with the current date, in your cases Fri Jan 03 2020 15:07:53. And when you do next.clear(), it sets to the inital epoch.
Epoch, also known as Unix timestamps, is the number of seconds (not
milliseconds!) that have elapsed since January 1, 1970 at 00:00:00 GMT
(1970-01-01 00:00:00 GMT).
I am calling a rest web service that accepts Date. On client side, i have calling this service using JDK 8 OffsetDateTime Class.
Value that is going from my client side : 2018-07-01T05:30+05:30
Value that is accepted by Service : 2018-07-01T08:00:00.000+0000
Below is the code:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(ZoneId.of("UTC")));
cal.set(2018, 05, 31);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.HOUR_OF_DAY, 0);
OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant(cal.getTime().toInstant(), ZoneId.systemDefault());
Value of offsetDateTime that is coming with above code is 2018-07-01T05:30+05:30.
I am in IST time zone.
Can someone help as to what needs to be done to change date to 2018-07-01T08:00:00.000+0000.
tl;dr
If you want 8 AM on first day of July at UTC…
OffsetDateTime.of(
2018 , 7 , 1 , // Date (year, month 1-12 is Jan-Dec, day-of-month)
8 , 0 , 0 , 0 , // Time (hour, minute, second, nano)
ZoneOffset.UTC // Offset-from-UTC (0 = UTC)
) // Returns a `OffsetDateTime` object.
.format( // Generates a `String` object with text representing the value of the `OffsetDateTime` object.
DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSZ" , Locale.US )
) // Returns a `String` object.
2018-07-01T08:00:00.000+0000
Avoid legacy date-time classes
Never use Calendar or Date classes. They were completely supplanted by the modern java.time classes such as OffsetDateTime. You are mixing the legacy classes with the modern, and that makes no sense.
java.time
Your Question is not clear about what are your inputs and what are your outputs versus your expectations.
If you goal is 8 AM on July 1 in UTC:
LocalDate ld = LocalDate.of( 2018 , Month.JULY , 1 ) ;
LocalTime lt = LocalTime.of( 8 , 0 ) ;
OffsetDateTime odt = OffsetDateTime.of( ld , lt , ZoneOffset.UTC ) ;
odt.toString(): 2018-07-01T08:00Z
That string format complies with ISO 8061 standard. If your destination refuses that input and accepts only 2018-07-01T08:00:00.000+0000, then we must defining a formatting pattern.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSZ" , Locale.US );
String output = odt.format( f );
2018-07-01T08:00:00.000+0000
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.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
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.
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 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). 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.
i think the below code will work
public static Date ConvertToGMT() {
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date utc = new Date(dateFormat.format(date));
return utc;
}
You can do it like so,
offsetDateTime.atZoneSameInstant(ZoneId.of("Asia/Kolkata"))
Update
If you need an instance of OffsetDateTime here it is.
offsetDateTime.atZoneSameInstant(ZoneId.of("Asia/Kolkata")).toOffsetDateTime();
It’s not the answer you asked for, but it may be the answer you prefer in the end: Check once more whether the service you are calling accepts the format that you are already giving it. Both formats conform with ISO 8601, so it seems that the service accepts this standard format. If so, it should accept yours too.
In any case, use OffsetDateTime and the other classes from java.time exclusively and avoid the old and outdated Calendar and TimeZone classes. Basil Bourque’s answer shows the good solution.
Link: Wikipedia article: ISO 8601
I want to generate a sequence of time in the following format (yyyy-mm-dd hh:mm:ss) with time interval of 15 min. I will give start date and end date.
Used the below code to test the same.
public static void main(String[] args) throws ParseException {
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-mm-dd HH:mm:ss");
DateTime dt1 = formatter.parseDateTime("2017-06-21 00:00:00");
DateTime dt2 = formatter.parseDateTime("2017-06-23 00:00:00");
DateTime dateTime1 = new DateTime(dt1);
DateTime dateTime2 = new DateTime(dt2);
List<Date> allDates = new ArrayList();
while( dateTime1.isBefore(dateTime2) ){
allDates.add( dateTime1.toDate() );
dateTime1 = dateTime1.plusMinutes(15);
System.out.println(dateTime1);
}
It generates output like below:
2017-01-21T00:15:00.000+05:30
Expected output is 2017-06-21 00:00:00 , it's not picking up the right date which I wanted.
tl;dr
Use java.time classes, which supplant the Joda-Time project. Convert input to standard format for easy parsing.
LocalDateTime.parse(
"2017-06-23 00:00:00".replace( " " , "T" )
).plus( Duration.ofMinutes( 15 ) )
Details
As noted by JB Nizet, you are using incorrect codes in your formatting pattern. Apparently you are guessing at the codes rather reading the documentation – an unwise practice. These codes have been covered hundreds of times on Stack Overflow, so apparently you are posting here without bothering to first search.
Joda-Time vs java.time
You are using the Joda-Time library. This project is now in maintenance mode, with the team advising migration to the java.time classes.
ISO 8601 standard
Your input strings nearly comply with the ISO 8601 standard. To fully comply, replace the SPACE in the middle with a T. The java.time classes use ISO 8601 formats by default when parsing/generating strings. So no need to define any formatting pattern.
Caveat about LocalDateTime
Your input lacks any indication of time zone or offset-from-UTC. So we will parse as LocalDateTime. Beware that a LocalDateTime is not a real moment, not an actual point on the timeline. Without the context of a time zone or offset, a LocalDateTime is unrealistic.
Solution
LocalDateTime start = LocalDateTime.parse( "2017-06-21 00:00:00".replace( " " , "T" ) ) ;
LocalDateTime stop = LocalDateTime.parse( "2017-06-23 00:00:00".replace( " " , "T" ) ) ;
For defensive programming, verify your start is before your stop. Something like stop.isAfter( start ).
On each loop, add your specified duration of 15 minutes.
Duration d = Duration.ofMinutes( 15 ) ;
LocalDateTime ldt = start ;
List< LocalDateTime > ldts = new ArrayList<>() ;
while( ! ldt.isAfter( stop ) ) { // "Not after" is a shorter way of saying "is earlier than or is equal to".
ldts.add( ldt ) ;
// Set up the next loop.
ldt = ldt.plus( d ) ;
}
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.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
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.
First of all, read the javadoc. The lowercase mm pattern corresponds to the minutes. To get the months, you need to use uppercase MM. So, your formatter will be like this:
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
And you don't need to do this:
DateTime dateTime1 = new DateTime(dt1);
It's redundant, because you're creating 2 identical objects. Just use the dates returned by parseDateTime method. Or just do:
DateTime dateTime1 = dt1;
And you've already created a DateTimeFormatter, so just use it to format the output as well. Instead of:
System.out.println(dateTime1);
Do this:
System.out.println(formatter.print(dateTime1));
The print method will return the dates in the format you want.
I'm not sure if you wanted to print the first date (2017-06-21 00:00:00). If you want this, just change the order of the plusMinutes and System.out.println lines.
New Java Date/Time API
Joda-Time is in maintainance mode and is being replaced by the new APIs, so I don't recommend start a new project with it. Even in joda's website it says: "Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310).".
So, if you can migrate your Joda-Time code, or starting a new project, consider using the new API. If you're using Java 8, you can use the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.
The logic is very similar. The only difference is that I used LocalDateTime class, and to convert it to a java.util.Date I need to know in what timezone it is. I used the system's default timezone, which is probably what you want (as your original code also uses the default timezone):
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime1 = LocalDateTime.parse("2017-06-21 00:00:00", formatter);
LocalDateTime dateTime2 = LocalDateTime.parse("2017-06-23 00:00:00", formatter);
List<Date> allDates = new ArrayList();
while (dateTime1.isBefore(dateTime2)) {
// get the date in the system default timezone and convert to java.util.Date
allDates.add(Date.from(dateTime1.atZone(ZoneId.systemDefault()).toInstant()));
dateTime1 = dateTime1.plusMinutes(15);
System.out.println(formatter.format(dateTime1));
}
In Java 8 the Date.from method is available. In ThreeTen Backport (Java 7 and Android), you can use the org.threeten.bp.DateTimeUtils class instead:
allDates.add(DateTimeUtils.toDate(dateTime1.atZone(ZoneId.systemDefault()).toInstant()));
I have to display a date in the format MM/dd/yyyy. The date to be displayed can be in any of the following formats
MM/dd/yyyy
MM/yyyy
yyyy
If only month and year are available and day is not available then I have to display the date in the format MM/__/yyyy leaving the day blank.
If only year is available and day and month are not available then I have to display the date in the format __/__/yyyy leaving day and month blank.
I'm able to display it properly if whole date is available i.e. day, month and year using mask formatter.
MaskFormatter formattedDate = new MaskFormatter("##'/##'/####");
but not able to display it if day or month is missing.
Is there any way to display the date leaving date and month blank?
java.time
The java.time classes built into Java 8 and later have a class for each of your needs:
LocalDate for date-only, without time-of-day, and without time zone.
YearMonth for a year and month but no date, and no time zone.
Year for just a year.
For example:
YearMonth ym = YearMonth.now( ZoneId.of( "Africa/Tunis" ) );
ym.toString(): 2018-02
All three offer a format method to which you pass a DateTimeFormatter object. You can define custom formatting patterns in that DateTimeFormatter. Search Stack Overflow as this has been covered many times already.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/__/uuuu" );
String output = ym.format( f );
02/__/2018
ISO 8601
By the way, consider using standard ISO 8601 formats to display these values as text. The format for a date is YYYY-MM-DD, and for a year-month, YYYY-MM.
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.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). 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.
I have a Date object in Java. Sometimes the date's year is set to 17. When I go to output it using a SimpleDateFormat, it gets printed out as 0017. All my years are going to be in the 2000's. Is there a way to check if the year is belowe a certain value and then add 2000 to it if it is? Then once you do that, how do you recreate the Date object to use the new year? Seems like everything in the Date object is deprecated.
I would use a Calendar:
Date myDate = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
int year = cal.get(Calendar.YEAR);
if(year < 2000)
cal.add(Calendar.YEAR, 2000); // add two thousand years
If you use Calendar or Joda Time (a better choice) you can get and set the year (or other fields)
Your year shouldn't be 17 in the first place. I would try to correct the problem at source rather than patch it later.
First of all, Date.getYear returns CurrentYear - 1900, not 2000, and it looks like you'll want to do that increment every time.
But since it's deprecated, you shouldn't use it in the first place, if possible. The API recommends you use the calendar class instead: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Calendar.html
java.time
If by Date you mean java.util.Date, that terribly designed class in now obsolete, years ago supplanted by the java.time classes defined in JSR 310.
Convert to its replacement, Instant, using new methods added to the old classes.
Instant instant = myJavaUtilDate.toInstant() ;
Both Instant and java.util.Date represent a moment in UTC. For any given moment, both time-of-day and date vary around the globe by zone. If you want to see the date through the wall-clock time of a particular time zone, apply ZoneId to get a ZonedDateTime.
ZoneID z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDatetTime zdt = instant.atZone( z ) ;
Now interrogate for the year.
int year = zdt.getYear() ;
Adjust. If that date in the different year is not valid (February 29 in non leap year), the ZonedDateTime class adjusts.
if( year < 1000 ) {
zdt = zdt.withYear( year + 2000 ) ; // You might also want to check for negative numbers. I'll omit that from this demo.
}
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.
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 adds 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 bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). 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.