add 1 month from current date using java.sql.Date - java

Hello i have a problem with the result of java.sql.Date. This is my code with adding 1 week from current date
Date kini = new Date();
java.sql.Date jadwalPengobatan = new java.sql.Date(kini.getTime()+7*24*60*60*1000);
If current date is 2016-02-27, then the result in my MySQL is 2016-03-05.
But if i want to add 1 month (for my case its always 31 days) from current date using this line code
java.sql.Date jadwalPengobatan = new java.sql.Date(kini.getTime()+31*24*60*60*1000);
It should be 2016-03-28 but in my MySQL result is 2016-02-05. Anyone can help me whats wrong with this result??

java.time
The other Answers use the outmoded old date-time classes. After proving to be confusing, troublesome, and flawed, they have been supplanted by the java.time framework in Java 8 and later.
Do not use the java.sql classes in your business logic. They are a messy extension of those old date-time classes, and are a badly-designed hack. Use them only for transferring your data in/out of the database. Convert to java.time types immediately.
To convert, use the new methods added to the old classes.
In the case of java.sql.Date, it is pretending to hold a date-only value without time-of-day nor time zone. The java.time classes include a true date-only value, LocalDate. To convert from java.sql.Date to java.time.LocalDate, call java.sql.Date::toLocalDate.
LocalDate ld = mySqlDate.toLocalDate();
Adding a true month is built-in.
LocalDate monthLater = ld.plusMonths( 1 );
Convert back to java.sql for storage in the database.
java.sql.Date sqlDate = java.sql.Date.valueOf( monthLater );
Hopefully some day we will see the JDBC drivers updated to support the java.time types directly. Then the java.sql types will fade away as old relics of the past. But until then we need to perform these java.sql ↔ java.time conversions.
Update: JDBC 4.2 and later provides for passing java.time types directly with PreparedStatement::setObject, and fetching with ResultSet::getObject. So no need for conversion to java.sql types.

Use Calendar:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
Date result = cal.getTime();

The problem with your solution is that you are not doing the calculations in long.
You have to replace 31*24*60*60*1000 with 31l*24l*60l*60l*1000l.
Here is the corrected code snippet:
public static void main (String[] args)
{
Date kini = new Date();
java.sql.Date jadwalPengobatan = new java.sql.Date(kini.getTime() + 31l*24l*60l*60l*1000l);
System.out.println(jadwalPengobatan);
}
Please note that this will only fix your calculation where you are adding 31 days to the current date. If you are looking to add a month which can be of 30, 28 or 29 days also then perhaps you should make use of Calendar.
Today's Date:
2016-02-27
Output:
2016-03-29

One solution to your problem would be to alter the date in MySQL using the DATE_ADD() function:
DATE_ADD(yourDate, INTERVAL 1 MONTH)

SimpleDateFormat date= new SimpleDateFormat("dd/MM/yyyy");
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.add(Calendar.MONTH, 1);
String output= date.format(calendar.getTime());
java.sql.Date jadwalPengobatan = new java.sql.Date(output);

You could do the following, using Calendar:
Date kini = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(kini);
cal.add(Calendar.DATE, 7); // add 10 days, e.g. 1 week
cal.add(Calendar.DATE, 31); // add 31 days, e.g. ~1 month
java.sql.Date jadwalPengobatan = new java.sql.Date(cal.getTime());
Also see this discussion.

Related

How to make gc.setTime() from GregorianCalendar fixed

Here is a part from my code:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(dateFormat.parse(jahr+"-"+monat+"-"+tag));
And now I want to print out some moving easter holidays in Germany.
gc.add(Calendar.DAY_OF_MONTH, -2);
System.out.println("Karfreitag;"+dateFormat.format(gc.getTime()));
gc.add(Calendar.DAY_OF_MONTH, +3);
System.out.println("Ostermontag;"+dateFormat.format(gc.getTime()));
gc.add(Calendar.DAY_OF_MONTH, +38);
To make it a bit clearer.
Eastersunday was on 16.04.2017 this year.
So the first print out is working fine, 'Karfreitag' is two days before eastersunday. So it was the 14.04.2017.
Moving on to eastermonday throws a problem. Eastermonday is the day after eastersunday. Unfortuanately I have to add +3 days because I overwrote the eastersunday date with the 'Karfreitag' date.
So I want to know if it is possible to make the date from eastersunday fix so that I have to change my 3th line into:
gc.add(Calendar.DAY_OF_MONTH, +1);
It think this could be very easy but I have no clue how to change this in a proper way.
As the add method changes the current calendar instance, one solution is to create another one, using the clone() method:
// clone it before changing it
GregorianCalendar other = (GregorianCalendar) gc.clone();
gc.add(Calendar.DAY_OF_MONTH, -2);
System.out.println("Karfreitag;" + dateFormat.format(gc.getTime()));
other.add(Calendar.DAY_OF_MONTH, 1);
System.out.println("Ostermontag;" + dateFormat.format(other.getTime()));
Java new Date/Time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java 6 or 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, you'll also need 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.
As you're dealing with dates (day/month/year), you can use the LocalDate class. In this new API, classes are immutable, so the methods that add a number of days always create another object:
LocalDate easter = LocalDate.parse("2017-04-16");
// minusDays and plusDays return a new LocalDate, keeping the original unchanged
System.out.println("Karfreitag;" + easter.minusDays(2));
System.out.println("Ostermontag;" + easter.plusDays(1));
The output will be:
Karfreitag;2017-04-14
Ostermontag;2017-04-17
If you have the day, month and year as int values, you can create a LocalDate using the of method:
int tag = 16;
int monat = 4;
int jahr = 2017;
// Easter
LocalDate easter = LocalDate.of(jahr, monat, tag);
Convert from/to GregorianCalendar
If you still need to work with GregorianCalendar, you can easily convert it from/to the new API. In Java 8 there are new methods to do the conversion, while in Java 6/7 ThreeTen Backport there's the org.threeten.bp.DateTimeUtils class:
// Java 8: convert calendar to local date
LocalDate dt = gc.toZonedDateTime().toLocalDate();
// Java 7: convert calendar to local date
LocalDate dt = DateTimeUtils.toZonedDateTime(gc).toLocalDate();
To convert the LocalDate back to GregorianCalendar is a little bit tricky. A LocalDate has only the date fields (day, month and year), while a GregorianCalendar represents a "full date": a date and time in a specific timezone.
So, when converting a LocalDate to a GregorianCalendar, you must make some assumptions about the time (hour, minutes, etc) and the timezone. One example is to set the time to midnight, and use the JVM default timezone:
// Java 8: convert local date to calendar (midnight in JVM default timezone)
GregorianCalendar cal = GregorianCalendar.from(dt.atStartOfDay(ZoneId.systemDefault()));
// Java 7: convert local date to calendar (midnight in JVM default timezone)
GregorianCalendar cal = DateTimeUtils.toGregorianCalendar(dt.atStartOfDay(ZoneId.systemDefault()));
You can also convert to any other time of the day and change the timezone to whatever you want:
// set to 10:30 AM in Berlin timezone
dt.atTime(10, 30).atZone(ZoneId.of("Europe/Berlin"));
Or you can use the ZonedDateTime returned by toZonedDateTime() directly, and extract the LocalDate part when printing:
// convert calendar to ZonedDateTime
ZonedDateTime z = gc.toZonedDateTime();
// print just the LocalDate part
System.out.println("Karfreitag;" + z.minusDays(2).toLocalDate());
System.out.println("Ostermontag;" + z.plusDays(1).toLocalDate());
// get the original calendar back
GregorianCalendar cal = GregorianCalendar.from(z);
This new API has lots of new types and allows you to choose the best for each case.
Start using java.time.LocalDate. It provide a LocalDate.plusDays(long) that return a copy of the instance.
Returns a copy of this LocalDate with the specified number of days added.
Like this :
LocalDate tomorrow = LocalDate.now().plusDays(1);
And you can get an instance using LocalDate.of(int, int, int) like :
LocalDate date = LocalDate.of(year, month, day);
NOTE: This is a shorter version of Hugo's answer, just realise that there were to part in his answer...
You can use DateUtils.addDays like this:
DateUtils.addDays(gc.getDate(), -2).getTime()
It needs a Date object (you can use gc.getDate() for this) and int number of days to add as arguments and also return a Date object without modifying your original gc.
System.out.println("Karfreitag;"+dateFormat.format(DateUtils.addDays(gc.getDate(), -2).getTime()));
System.out.println("Ostermontag;"+dateFormat.format(DateUtils.addDays(gc.getDate(), 3).getTime()));
System.out.println("something else;"+dateFormat.format(DateUtils.addDays(gc.getDate(), 38).getTime()));
In Android its available from API level 3,in Java you'll have to use Apache Commons

how to get today's date and add 7 days to it and the insert into oracle sql?

I am working on a program where I want to retrieve today's date in a servlet, then add some days to it say 7 days and then finally insert into oracle SQL database.
I am using prepared statement to do the call. Till now I have the current date using the following code.
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
How do I add 7 days to it and then insert it in the db?
Based on your date format dd/MM/yyyy, I'm assuming that you're interested in only date but not date-time (timestamp like dd/MM/yyyy hh:mm:ss), you can do it easily in Java 8 with the new Date Time API in java.time package like this
LocalDate date = LocalDate.now();
date = date.plusDays(7);
In your PreparedStatement, you can use setObject like this
PreparedStatement ps = Connection.prepareStatement(sql);
ps.setObject(2,date); // 2 is the place holder for your date column
Note that these new classes are immutable like String, so any change on them will return a new object and you need to capture the return value after calling any method.
For more information, have a look at the API here
Get calendar instance, call setTime, call add, call getTime
https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#setTime%28java.util.Date%29
https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#add%28int,%20int%29
Alternately add the days to your prepared statement ... see This SO question as example
Calendar cal = Calendar.getInstance();
cal.clear(Calendar.HOUR_OF_DAY);
cal.clear(Calendar.AM_PM);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
int days = 7;
// Add days
calendar.add(Calendar.DAY_OF_MONTH, days);
System.out.println(calendar.getTime());
For adding let's say 7 days, Following code snippet would work:
Calendar cal = Calendar.getInstance();
//in below line of code, date is in which which you want to add 7 number of days
cal.setTime(date);
cal.add(Calendar.DATE, 7);
java.util.Date utilDate = cal.getTime();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
Now you can use sqlDate value in your insert query.
Hope it helps :)
You could let the DB do the arithmetic for you and do this:
PreparedStatement ps = null;
try {
String sql = "INSERT INTO mytable (id, datecolumn) VALUES (?, trunc(?) + 7)";
ps = myConnection.prepareStatement(sql);
ps.setString(1, id);
ps.setDate(2, new Date());
// if your DB has a different timezone than your app server,
// you should use this instead
// ps.setDate(2, new Date(), Calendar.getInstance("<TZ of DB>"));
ps.executeUpdate();
} finally {
if (ps != null) {
ps.close();
}
}
This code inserts a date value to the target column having the time part set to zero (using Oracle's trunc function) and the date incremented by seven days.
It is important to note that if the timezone of your database is different from the JVM's, you should use the setDate overload that takes the TZ into account.
Use java.util.Calendar class Get the days (depends upon your requirement) add desired days to it
Days can be Day in month or day in week or day in year I think for your requirement days in month is better...
java.util.Date date = new Date();
Calendar cal = Calendar.getInstance();
//date = cal.getTime();
int days = cal.get(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, days+7);
date = cal.getTime();
System.out.println(date);
java.time
The modern way is with java.time classes. The Question and other Answers use the troublesome old legacy date-time classes.
LocalDate
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.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
Easy to do date math.
LocalDate weekLater = today.plusWeeks( 1 );
Database
If you have a database driver compliant with JDBC 4.2 or later, you should be able to pass the LocalDate object through JDBC with the PreparedStatement::setObject method.
myPreparedStatement.setObject( … , weekLater );
If not, you must convert to the old java.sql.Date class.
java.sql.Date sqlDate = java.sql.Date.valueOf( weekLater );
myPreparedStatement.setDate( … , sqlDate );
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, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
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 and 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 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….
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.

Generate month in character from calendar java into a variable

Good day all,
I was trying to create a date variable by using Calendar java, the following is my example code:
long day = System.currentTimeMillis();
Calendar cal = Calendar.getInstance();
java.text.SimpleDateFormat month = new java.text.SimpleDateFormat("MMM"); // not sure how to assign this value inside
cal.setTimeInMillis(day);
cal.set(Calendar.HOUR_OF_DAY, 00);
cal.set(Calendar.MINUTE, 00);
cal.set(Calendar.SECOND, 00);
cal.set(Calendar.MILLISECOND, 000);
Date todayDate = cal.getTime();
Timestamp current = new Timestamp(todayDate.getTime());
However, the value of current I get is 2014-01-13 00:00:00.0. I prefer to set the 01 to Jan instead.
Any ideas on this?
You mean something like so?
long day = System.currentTimeMillis();
Calendar cal = Calendar.getInstance();
java.text.SimpleDateFormat month = new java.text.SimpleDateFormat("yyyy-MMM-dd HH:mm:ss:S"); // not sure how to assign this value inside
cal.setTimeInMillis(day);
cal.set(Calendar.HOUR_OF_DAY, 00);
cal.set(Calendar.MINUTE, 00);
cal.set(Calendar.SECOND, 00);
cal.set(Calendar.MILLISECOND, 000);
Date todayDate = cal.getTime();
Timestamp current = new Timestamp(todayDate.getTime());
System.out.println(month.format(current));
Yields:
2014-Jan-13 00:00:00:0
Please check the SimpleDateFormat for more formatting options.
You can try this
long day = System.currentTimeMillis();
Calendar cal = Calendar.getInstance();
SimpleDateFormat month = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss:S");
cal.setTimeInMillis(day);
cal.set(Calendar.HOUR_OF_DAY, 00);
cal.set(Calendar.MINUTE, 00);
cal.set(Calendar.SECOND, 00);
cal.set(Calendar.MILLISECOND, 000);
Date todayDate = cal.getTime();
Timestamp current = new Timestamp(todayDate.getTime());
System.out.println(month.format(current));
Now out put:
2014-Jan-13 00:00:00:0
ideone
// not sure how to assign this value inside
there you go.. ;)
yy = year (2 digit)
yyyy = year (4 digit)
M = month of the year
MM = month of the year (leading 0)
MMM = month of the year (short text)
MMMM = month of the year (full text)
d = day of the month
dd = day of the month (leading 0)
h = hour (1-12)
H = hour (0-23)
m = minute of the hour
s = second of the minute
S = milisecond
E = day of the week (short)
EEEE = day of the week (full)
D = day of the Year
Additional link to the SimpleDateFormat class
Since you are looking for current date, you do not need currentTimeMillis().
Instead you can do the following to get the desired output.
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss.S");
System.out.println(sdf.format(cal.getTime()));
tl;dr
Avoid the troublesome legacy date-time classes. Use only java.time classes.
LocalDate.now() // Determine the current date as seen in the wall-clock time in use by JVM’s current default time zone. Better to specify explicitly your desired/expected time zone.
.getMonth() // Get the `Month` enum object representing the month of that `LocalDate` object’s date value.
.getDisplayName( // Let the `Month` enum object automatically localize to generate the string of the name of the month.
TextStyle.SHORT , // Specify how long or abbreviate you want the text of the name of the month.
Locale.US // Specify a `Locale` to determine the human language and cultural norms to be used in localizing the name of the month.
) // Return a String.
Jan
java.time
The modern approach uses java.time classes.
Getting the current month means determining the current date. And getting the current date requires a time zone, as for any given moment the date varies around the globe by zone.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate ld = LocalDate.now( z ) ;
Month m = ld.getMonth();
Let the Month enum automatically localize the name of the month. Control abbreviation by passing a TextStyle.
String output = m.getDisplayName( TextStyle.SHORT , Locale.US );
Apr
Date with time
If your goal is to combine a time-of-day with your date, use ZonedDateTime class. You must specify a time zone to determine the first moment of the day. The day does not start at 00:00:00 on some dates in some zones.
ZonedDateTime zdt = ld.atStartOfDay( z ) ; // Determine the first moment of the day.
Do not use java.sql.Timestamp for the purpose of generating a String. Use the DateTimeFormatter class, documented in many other Answers on Stack Overflow.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MMM-dd HH:mm:ss" , Locale.US ) ;
String output = zdt.format( f ) ;
Or just call ZonedDateTime::toString to generate a String in standard ISO 8601 format, wisely extended to append the name of the zone in square brackets.
String output = zdt.toString() ;
Indeed, do not use Timestamp at all. That class is intended for use with databases, and is now replaced by Instant as of JDBC 4.2 and later.
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, 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 (<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.

Date object to Calendar [Java]

I have a class Movie
in it i have a start Date, a duration and a stop Date.
Start and stop Date are Date Objects (private Date startDate ...)
(It's an assignment so i cant change that)
now I want to automatically calculate the stopDate by adding the duration (in min) to the startDate.
By my knowledge working with the time manipulating functions of Date is deprecated hence bad practice but on the other side i see no way to convert the Date object to a calendar object in order to manipulate the time and reconvert it to a Date object.
Is there a way? And if there is what would be best practice
What you could do is creating an instance of a GregorianCalendar and then set the Date as a start time:
Date date;
Calendar myCal = new GregorianCalendar();
myCal.setTime(date);
However, another approach is to not use Date at all. You could use an approach like this:
private Calendar startTime;
private long duration;
private long startNanos; //Nano-second precision, could be less precise
...
this.startTime = Calendar.getInstance();
this.duration = 0;
this.startNanos = System.nanoTime();
public void setEndTime() {
this.duration = System.nanoTime() - this.startNanos;
}
public Calendar getStartTime() {
return this.startTime;
}
public long getDuration() {
return this.duration;
}
In this way you can access both the start time and get the duration from start to stop. The precision is up to you of course.
Calendar tCalendar = Calendar.getInstance();
tCalendar.setTime(date);
date is a java.util.Date object. You may use Calendar.getInstance() as well to obtain the Calendar instance(much more efficient).
Calendar.setTime()
It's often useful to look at the signature and description of API methods, not just their name :) - Even in the Java standard API, names can sometimes be misleading.
You don't need to convert to Calendar for this, you can just use getTime()/setTime() instead.
getTime():
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
setTime(long time) : Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT. )
There are 1000 milliseconds in a second, and 60 seconds in a minute. Just do the math.
Date now = new Date();
Date oneMinuteInFuture = new Date(now.getTime() + 1000L * 60);
System.out.println(now);
System.out.println(oneMinuteInFuture);
The L suffix in 1000 signifies that it's a long literal; these calculations usually overflows int easily.
tl;dr
Instant stop =
myUtilDateStart.toInstant()
.plus( Duration.ofMinutes( x ) )
;
java.time
Other Answers are correct, especially the Answer by Borgwardt. But those Answers use outmoded legacy classes.
The original date-time classes bundled with Java have been supplanted with java.time classes. Perform your business logic in java.time types. Convert to the old types only where needed to work with old code not yet updated to handle java.time types.
If your Calendar is actually a GregorianCalendar you can convert to a ZonedDateTime. Find new methods added to the old classes to facilitate conversion to/from java.time types.
if( myUtilCalendar instanceof GregorianCalendar ) {
GregorianCalendar gregCal = (GregorianCalendar) myUtilCalendar; // Downcasting from the interface to the concrete class.
ZonedDateTime zdt = gregCal.toZonedDateTime(); // Create `ZonedDateTime` with same time zone info found in the `GregorianCalendar`
end if
If your Calendar is not a Gregorian, call toInstant to get an Instant object. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = myCal.toInstant();
Similarly, if starting with a java.util.Date object, convert to an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = myUtilDate.toInstant();
Apply a time zone to get a ZonedDateTime.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
To get a java.util.Date object, go through the Instant.
java.util.Date utilDate = java.util.Date.from( zdt.toInstant() );
For more discussion of converting between the legacy date-time types and java.time, and a nifty diagram, see my Answer to another Question.
Duration
Represent the span of time as a Duration object. Your input for the duration is a number of minutes as mentioned in the Question.
Duration d = Duration.ofMinutes( yourMinutesGoHere );
You can add that to the start to determine the stop.
Instant stop = startInstant.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 java.time.
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 and 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 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….
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.
something like
movie.setStopDate(movie.getStartDate() + movie.getDurationInMinutes()* 60000);
Here is a full example on how to transform your date in different types:
Date date = Calendar.getInstance().getTime();
// Display a date in day, month, year format
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String today = formatter.format(date);
System.out.println("Today : " + today);
// Display date with day name in a short format
formatter = new SimpleDateFormat("EEE, dd/MM/yyyy");
today = formatter.format(date);
System.out.println("Today : " + today);
// Display date with a short day and month name
formatter = new SimpleDateFormat("EEE, dd MMM yyyy");
today = formatter.format(date);
System.out.println("Today : " + today);
// Formatting date with full day and month name and show time up to
// milliseconds with AM/PM
formatter = new SimpleDateFormat("EEEE, dd MMMM yyyy, hh:mm:ss.SSS a");
today = formatter.format(date);
System.out.println("Today : " + today);
Extension for converting date to calendar in Kotlin.
fun Date?.toCalendar(): Calendar? {
return this?.let { date ->
val calendar = Calendar.getInstance()
calendar.time = date
calendar
}
}

Getting today's date in java - I've tried the regular ways

I need today's date - and zero anything else (" 05/06/08 00:00:00 ")
I've tried
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, 0);
Date date1 = calendar.getTime();
System.out.println(date1);
Run: (This is seriously messed up)
If the hour on the computer is < 12:00 at noon : Sun Mar 08 00:44:39 IST 2009
If the hour on the computer is > 12:00 at noon : Sun Mar 08 12:46:53 IST 2009
So I gave this up.
All the Date's setters are deprecated (except the epoch time) - so I don't want to use them either
The only thing I could think of is
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String sDate = dateFormat.format(calendar.getTime());
Date today = dateFormat.parse(sDate);
But this is such a lame code I can't bring myself to write it.
Any other option?
Thanks!
I use this:
public static Date startOfDay(Date date) {
Calendar dCal = Calendar.getInstance();
dCal.setTime(date);
dCal.set(Calendar.HOUR_OF_DAY, 0);
dCal.set(Calendar.MINUTE, 0);
dCal.set(Calendar.SECOND, 0);
dCal.set(Calendar.MILLISECOND, 0);
return dCal.getTime();
}
My standard advice for Java date/time questions: don't use java.util.{Calendar,Date}. Use Joda Time. That way you can represent a date as a date (with no associated time zone), instead of a date/time. Or you could use a DateMidnight if that's what you want to represent. (Be careful of combinations of time zone and date where there is no midnight though...)
What do you need to use the Date with? If you can get away with changing to use Joda throughout, that's great. Otherwise, you can use Joda to do what you want and then convert to milliseconds (and then to java.util.Date) when you really need to.
(Michael's solution when using Date/Calendar is fine if you really want to stick within a broken API... but I can't overstate how much better Joda is...)
You should use HOUR_OF_DAY instead of HOUR and combine it with MINUTE and SECOND also.
import java.util.Calendar;
import static java.util.Calendar.HOUR_OF_DAY;
import static java.util.Calendar.MINUTE;
import static java.util.Calendar.SECOND;
import static java.util.Calendar.MILLISECOND;
public class Today {
public static void main( String [] args ) {
Calendar cal = Calendar.getInstance();
cal.set( HOUR_OF_DAY, 0 );
cal.set( MINUTE, 0 );
cal.set( SECOND, 0 );
cal.set( MILLISECOND, 0 );
System.out.println( cal.getTime() );
}
}
The results you are getting are due to HOUR is used to AM/PM while HOUR_OF_DAY is 24 hrs.
HOUR_OF_DAY:
Field number for get and set indicating the hour of the day. HOUR_OF_DAY is used for the 24-hour clock. E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22.
HOUR:
Field number for get and set indicating the hour of the morning or afternoon. HOUR is used for the 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12. E.g., at 10:04:15.250 PM the HOUR is 10.
The time component is not just hours (and Calendar.HOUR is, as you have noticed, AM/PM).
You need to set all of the time fields to 0: HOUR_OF_DAY, MINUTE, SECOND, MILLISECOND.
See Apache's commons-lang DateUtils.truncate()
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
The modern Date-Time API has many types which truly represent a date or time or date-time in a specific timezone. You can choose from the following options as per your specific requirement:
If you are looking for a type that represents a date without a timezone, you can use LocalDate.now. The good news is that its variant, LocalDate#now(ZoneId) returns the current date from the system clock in the specified time-zone.
If you are looking for an object that represents a date without a timezone, and with time units set to zero, you can call LocalDate#atStartOfDay on the object obtained with Option#1.
If you are looking for an Instant representing the Date-Time object obtained with Option#2, you can attach this object with ZoneId.of("Etc/UTC") using LocalDateTime#atZone to obtain a ZonedDateTime and convert the same into an Instant using ZonedDateTime#toInstant.
Demo:
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
LocalDate todayInSystemTz = LocalDate.now();
System.out.println(todayInSystemTz);
LocalDate todayInIndia = LocalDate.now(ZoneId.of("Asia/Kolkata"));
System.out.println(todayInIndia);
LocalDateTime todayInSystemTzWithZeroTimeUnits = todayInSystemTz.atStartOfDay();
System.out.println(todayInSystemTzWithZeroTimeUnits);
ZonedDateTime todayInUtcWithZeroTimeUnits = todayInSystemTzWithZeroTimeUnits.atZone(ZoneId.of("Etc/UTC"));
System.out.println(todayInUtcWithZeroTimeUnits);
Instant instant = todayInUtcWithZeroTimeUnits.toInstant();
System.out.println(instant);
// Can I represent the obtained Instant in India?
System.out.println(instant.atZone(ZoneId.of("Asia/Kolkata")));
// Can I represent the obtained Instant in New York?
System.out.println(instant.atZone(ZoneId.of("America/New_York")));
}
}
Output:
2021-06-20
2021-06-20
2021-06-20T00:00
2021-06-20T00:00Z[Etc/UTC]
2021-06-20T00:00:00Z
2021-06-20T05:30+05:30[Asia/Kolkata]
2021-06-19T20:00-04:00[America/New_York]
ONLINE DEMO
The Z in the output is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).
For any reason, if you need to convert this object of Instant to an object of java.util.Date**, you can do so as follows:
Date date = Date.from(instant);
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
**
A java.util.Date object simply represents the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT (or UTC). Since it does not hold any timezone information, its toString function applies the JVM's timezone to return a String in the format, EEE MMM dd HH:mm:ss zzz yyyy, derived from this milliseconds value. To get the String representation of the java.util.Date object in a different format and timezone, you need to use SimpleDateFormat with the desired format and the applicable timezone e.g.
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String strDateNewYork = sdf.format(date);
sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String strDateUtc = sdf.format(date);
As mentioned above you should use
Calendar.HOUR_OF_DAY
As opposed to
Calendar.HOUR
Also you need to clear out the other fields (Calendar.MINUTE, Calendar.SECOND, and Calendar.MILLISECOND) by setting them to zero.
Sorry there's no easy way here. A pain, and that's why they're working on a new API for Java 7 I believe based on Joda Time.
...or you can do it the hacker way:
long MS_PER_DAY = 86400000L;
Date dateTime=new Date();
long offset = TimeZone.getDefault().getOffset(dateTime.getTime());
Date date= new Date(((dateTime.getTime()+offset)/MS_PER_DAY)*MS_PER_DAY-offset);
I know this is a very old question, no longer active, but it came to be on the top when I searched Google.
While all advise is very good, I can't believe no one simply answered:
Date date = new Date(System.currentTimeMillis());
System.out.println(date);
Which returns effectively, today's date.
Why the string manipulation?
Can you not just set the values you need on the Calendar object before converting to a Date using getTime()?
Another vote for JodaTime.
java.util.Date and Calendar are so bad they are broken. (And SimpleDateFormat is rubbish too!)
For what it's worth, Java 7 will include a new date time library based strongly around JodaTime.

Categories