Dates in Java, how to manipulate the year? - java

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.

Related

How to cast date and time in Android

In my application i want get some data from server and i should cast date and time!
I receive date and time with this format end_date: "2020-04-08 13:11:14" from server.
I want get now date and time from my device and to calculate with above date (end_date), if this time under 24h i should show for example 15 hour later, but if this time more than 24h i should show 2 days later!
But i don't know how can i it?
Can you help me with send code or send to me other tutorials?!
I searched that but I didn't find anything.
java.time
The modern approach uses java.time classes.
Parse the input string as a LocalDateTime.
To parse, replace the SPACE in the middle with a T to comply with ISO 8601 standard.
String input = "2020-04-08 13:11:14".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
Your input lacks an indicator of any time zone or offset-from-UTC. So we do not know if this was meant to be 1 PM in Tokyo Japan, 1 PM in Toulouse France, or 1 PM in Toledo Ohio US. So you cannot reliably compare this to the current date and time.
If you want to presume this string was meant to tell time in your time zone, then assign a time zone to get a ZonedDateTime.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime then = ldt.atZone( z ) ;
Capture the current moment in the same zone.
ZonedDateTime now = ZonedDateTime.now( z ) ;
Calculate 24 hours later.
ZonedDateTime twentyFourHoursFuture = now.plusHours( 24 ) ;
Compare.
boolean within24Hours = then.isBefore( twentyFourHoursFuture ) ;
Determine elapsed time using the Duration class.
Duration duration = Duration.between( then , now ) ;
If you want to trust the JVM’s current default time zone, call ZoneId.systemDefault. Beware that this default can be changed by other Java code during execution of your app.
ZoneId z = ZoneId.systemDefault() ;
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.
Try using the datetime library, or you can see this answer.
Also if you can choose, it's a good habit to pass the times in UTC from/to the server, it'll save some localization and timezone troubles.

substract one millisecond to the given Date in Java

i have a Date field expiryDate with value Thu Nov 21 00:00:00 IST 2019 But i am trying to get the endDate time to the before to the day by removing a millisecond from the time as Thu Nov 20 23:59:59 IST 2019
do we have any methods to remove a millisecond from the given Date.
java.time
Avoid the terrible date-time classes that are now legacy as of JSR 310. Now supplanted by the modern java.time classes.
You can easily convert back and forth. Call new conversion methods addd to the old classes.
Instant instant = myJavaUtilDate.toInstant() ;
And back again.
java.util.Date myJavaUtilDate = Date.from( instant ) ;
Subtract a millisecond.
Instant oneMilliEarlier = instant.minusMillis( 1 ) ;
Half-Open
But I suggest you not take this approach. Do not track a span of time by its last moment.
Your attempt to track the last moment of the day is problematic. You are losing that last millisecond of time. Doing so leaves a gap until the first moment of the next day. And when switching to a finer time slicing such as microseconds used by some systems such as databases like Postgres, and the nanoseconds used by other software such as the java.time classes, you have a worse problem.
A better approach is the Half-Open approach commonly used in date-time handling. The beginning of a span-of-time is inclusive while the ending is exclusive.
So an entire day starts at the first moment of the day, typically at 00:00:00 (but not always!), and runs up to, but does not include, the first moment of the next day.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
ZonedDateTime start = zdt.toLocalDate().atStartOfDay( z ) ;
ZonedDateTime stop = start.plusDays( 1 ) ;
Tip: For working with such spans of time, add the ThreeTen-Extra library to access the Interval class.
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.
yes. i just tried with the above mehtod getTime() returns milliseconds to the given date.
and substracting a millisecond is giving me a correct output.
new Date(milliseconds) giving me the Date format.
Thanks #Elliott Frisch

GregorianCalendar Class in Java

I am trying to get current time in other time zone. I used this code for this:
GregorianCalendar calender = new
GregorianCalendar(TimeZone.getTimeZone("Asia/Bangkok"));
System.out.println(calender.getTime());
But, when I am running this code, this code provides the current time in CET as the time in my local machine is in CET.
I am confused. Then why there is scope to provide a TimeZone in constructor?
Ahh, the joys of the Java Date/Time API ...
What you want (aside from a better API, such as Joda Time) is a DateFormat. It can print dates in a time zone you specify. You don't need Calendar for that.
dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Bangkok"));
dateFormat.format(new Date());
Calendar is for time manipulations and calculations. For example "set the time to 10 AM". Then it needs the timezone.
When you are done with these calculations, then you can get the result by calling calendar.getTime() which returns a Date.
A Date is essentially a universal timestamp (in milliseconds since 1970, with no timezone information attached or relevant). If you call toString on a Date it will just print something in your default timezone. For more control, use DateFormat.
What you are doing right now is:
Getting a calendar in Bangkok time zone
get the Date object for this time( which is in ms since some date January 1, 1970, 00:00:00 GMT)
print out this Date in your timezone (Date.toString())
You should use a Formatter class to get the result you want. e.g. SimpleDateFormat
An alternative solution would be to use a less confusing Date/Time library. e.g. JodaTime or the new java.time package of Java8
tl;dr
ZonedDateTime.now( ZoneId.of( "Asia/Bangkok" ) )
java.time
The legacy date-time classes you are using are simply terrible, flawed in design and in implementation, built by people who did not understand date-time handling. Avoid those classes entirely.
Use only the modern java.time classes defined in JSR 310.
ZoneId z = ZoneId.of( "Asia/Bangkok" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Generate text in standard ISO 8601 format, wisely extended to append the name of the time zone in square brackets.
String output = zdt.toString() ;
For other formats, use DateTimeFormatter as seen on hundreds of other Questions and Answers.
See this code run live at IdeOne.com.
2020-02-15T12:27:31.118127+07:00[Asia/Bangkok]
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.

Decrementing month from january to december last year in java

I'm have a problem going from january back to december I tried various things but im getting the nullexception. i'm using a button and put a mouselistener so everytime i click it, it decreament a month. but after january it won't decrement to december even i change the year before check the month. here's what I did.
Button btnNewButton = new Button(composite, SWT.NONE);
btnNewButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseUp(MouseEvent e) {
moveCalendar("down");
}
});
then here's my moveCalendar..
public void moveCalendar(String move)
{
Calendar cal = GregorianCalendar.getInstance();
resetBox();
if(move.equals("down") )
{
dummyMonth--;
if(dummyMonth < 0)
{
dummyMonth = 11;
dummyYear--;
}
}
else
{
dummyMonth++;
if(dummyMonth > 11)
{
dummyMonth = 0;
dummyYear++;
}
}
cal.set(Calendar.YEAR,dummyYear);
setYear(dummyYear);
cal.set(Calendar.MONTH,dummyMonth);
setMonth(dummyMonth);
int dy = getFirstDay(cal.get(Calendar.MONTH),cal.get(Calendar.YEAR));
int daysMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
populateCalendar(dy-1,daysMonth,cal.get(Calendar.DAY_OF_MONTH),dummyMonth);
}
I get nullexception.. any suggestion what's happening?
Try using the Joda-Time library.
It has much better support for date and time manipulation than the stock java classes — so much so that it's the basis for the new standard dates and times API introduced in Java 8. If you're using Java 8 or higher, use the java.time api instead.
In Joda-Time, you can easily move to the previous month with code like this:
YearMonth date = new YearMonth("2014-01");
date = date.minusMonths(1); //will equal 2013-11
Your question doesn't say whether you're just dealing with years and months, or with an exact date (year, month, and day) but either way you would use a minusMonths method, just with a different class (for an exact date use the LocalDate class, for example).
To integrate with the UI controls properly, you would populate the controls after you've finished manipulating the date object by setting each control to the correct value from the date object.
This approach will be much easier than dealing with Calendar.
Try using the Calendar.add() method, for example:
cal.add(Calendar.MONTH, -1);
See http://www.tutorialspoint.com/java/util/calendar_add.htm
tl;dr
LocalDate
.of( 2020 , Month.JANUARY , 20 )
.minusMonths( 1 )
java.time
The modern approach uses the java.time classes that years ago supplanted the terrible Calendar & Date classes.
For a date-only value, without time-of-day and without time zone, use LocalDate.
LocalDate localDate = LocalDate.of( 2020 , Month.JANUARY , 20 ) ;
To do date-math, call the plus… & minus… methods.
LocalDate monthAgo = localDate.minusMonths( 1 ) ; // Get same day-of-month in the previous month.
Or use a Period to represent a span-of-time unattached to the timeline.
Period p = Period.ofMonths( 1 ) ;
LocalDate earlier = localDate.minus( p ) ;
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.
Used Java 8 Date and time API as follows :
LocalDateTime dt2= LocalDateTime.of(2019,10,20, 12,45);
System.out.println(dt2); //2019-10-20T12:45
System.out.println(dt2.minusMonths(11));//2018-11-20T12:45

SimpleDateFormat parse returns wrong value

I have this code:
public static String formatMinSecOrHourMinSec(final String length) {
try {
final SimpleDateFormat hhmmss = new SimpleDateFormat("HH:mm:ss", Locale.GERMAN);
final Date date = hhmmss.parse(length);
final GregorianCalendar gc0 = new GregorianCalendar(Locale.GERMAN);
gc0.setTime(date);
if(gc0.getTimeInMillis() >= 3600 * 1000){
return hhmmss.format(gc0.getTime());
}else{
final SimpleDateFormat mmss = new SimpleDateFormat("mm:ss");
return mmss.format(gc0.getTime());
}
} catch (final ParseException e) {
LOGGER.debug("Konnte die Länge nicht parsen: " + length + "\n" + e);
return length;
}
}
I estimate that it returns 01:29:00 if length is set to 01:29:00 but it returns 29:00. This is because gc0.getTimeInMillis() returns one hour less (3600 * 1000) than expected. What am I doing wrong ?
this is because java.util.Date is using your default time zone. (print time in ms from date and you will see).
To fix it try:
final SimpleDateFormat hhmmss = new SimpleDateFormat("HH:mm:ss");
hhmmss.setTimeZone(TimeZone.getTimeZone("UTC"));
tl;dr
Do not conflate a span-of-time with a time-of-day. Two different concepts deserve two different classes. A span-of-time is represented by the Duration (or Period) class.
Duration
.ofHours( 1 )
.plusMinutes( 29 )
…or…
Duration
.parse( "PT1H29M" )
Wrong classes
First, you are using inappropriate classes. Apparently you are trying to track a span-of-time but are using time-of-day to do so. A span and a time are two different concepts. Mixing the two leads to ambiguity, confusion, and errors.
Second, you are using terrible old classes that were supplanted years ago by the java.time classes. Never use SimpleDateFormat, GregorianCalendar, etc.
Span-of-time
The correct class for a span-of-time in the range of hours-minutes-seconds is Duration. For a range of years-months-days, use Period.
You can instantiate your Duration from numbers of hours and minutes.
Duration d = Duration.ofHours( 1 ).plusMinutes( 29 ) ;
Or you can parse a string in standard ISO 8601 format, PnYnMnDTnHnMnS.
Duration d = Duration.parse( "PT1H29M" ) ;
Date-Time math
You can do math with date-time values. Perhaps you want to know when is an hour and twenty-nine minutes from now.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ; // Capture the current moment as seen though the wall-clock time used by the people of some particular region.
ZonedDateTime later = now.plus( d ) ; // Add a span-of-time to determine a later moment (or an earlier moment if the `Duration` is negative).
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.

Categories

Resources