I'm using a Gregorian Calendar to set a specific date and time to an application using the set function of the Gregorian Calendar. When i use the getTime() method, it gives me the right output however when i try to access the Hour_Of_Day and Minute it gives a wrong number.
Calendar time = new GregorianCalendar();
time.set(2010, Calendar.JANUARY, 1, 7, 20,0);
hour = time.HOUR_OF_DAY;
minute = time.MINUTE;
The hour gives an output of 11 and the minute gives an a value of 12.
Any suggestions on how to fix this?
Thanks
Your code is just assigning hour/minute to constants. You need to call Calendar.get(int):
hour = time.get(Calendar.HOUR_OF_DAY);
minute = time.get(Calendar.MINUTE);
tl;dr
myGregCal
.toZonedDateTime() // Convert from legacy class GregorianCalendar to modern ZonedDateTime.
.getHour() // Get hour-of-day, 0-23.
java.time
Much easier with the modern java.time classes that replace those troublesome old legacy date-time classes.
The ZonedDateTime class represents a moment on the timeline in a specific time zone with a resolution of nanoseconds.
Convert from your GregorianCalendar using new methods added to the old classes.
ZonedDateTime zdt = myGregCal.toZonedDateTime() ;
Or start fresh without the GregorianCalendar class.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.of( 2010 , Month.JANUARY , 1 , 7 , 20 , 0 , 0 , z );
If you want to work with just the time-of-day portion, extract a LocalTime.
LocalTime localTime = zdt.toLocalTime() ;
If you really want the integer numbers of hours and minutes, you can interrogate for those.
int hour = zdt.getHour();
int minute = zdt.getMinute();
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 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 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
I have a DateTime widget with 3/9/2017. Based on the documentation for DateTime, I don't see a way to determine the day of the week. I'll eventually need a string parsed in this format "Wed Feb 22 14:57:34 UTC 2017" from the DateTime widget, but the first step is to get the day of the week. Is there a way to do this outside of making my own function? And if not, what would you recommend as the best approach for the function, since days of the week are not consistent to dates from year to year?
Let me know if you need any addition information.
Thank you!
Use java.util.Calendar:
Calendar c = Calendar.getInstance();
c.setTime(yourDate);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
if you need the output to be Tue rather than 3 (Days of week are indexed starting at 1), instead of going through a calendar, just reformat the string: new SimpleDateFormat("EE").format(date) (EE meaning "day of week, short version")
Documentation
tl;dr
LocalDate.of( 2017 , Month.MARCH , 9 )
.getDayOfWeek()
.getDisplayName( TextStyle.FULL , Locale.ITALY )
Or…
OffsetDateTime.now( ZoneOffset.UTC )
.format( DateTimeFormatter.RFC_1123_DATE_TIME )
java.time
The modern approach uses the java.time classes that supplanted the troublesome old date-time classes.
The DayOfWeek enum defines seven objects, one for each day of the week, Monday-Sunday.
The LocalDate class represents a date-only value without time-of-day and without time zone.
DayOfWeek dow = LocalDate.now().getDayOfWeek() ;
Generate a string of the localized name.
String output = dow.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ; // Or Locale.US etc.
To generate your longer string for a moment, use DateTimeFormatter to specify a custom pattern, use a built-in pattern, or automatically localize.
String output = OffsetDateTime.now( ZoneOffset.UTC ).format( DateTimeFormatter.RFC_1123_DATE_TIME ) ;
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, 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.
I'm trying to set the time to epoch date time in java. how can I do this? so that I could get year months days etc out of the epoch date time.
use new Date(0L);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(sdf.format(new Date(0L)));
Take care of your timezone cause it will change depends on what you have by default.
UPDATE
In java 8 you can use the new java.time library
You have this constant Instant.EPOCH
As I understand, you only want to store it in some variable? So use
Date epoch = new Date(0);
try this
Calendar c = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
c.setTimeInMillis(0);
int day = c.get(Calendar.DATE);
int month = c.get(Calendar.MONTH) + 1;
int year = c.get(Calendar.YEAR);
tl;dr
Instant.EPOCH
Using java.time
The troublesome old date-time classes including Date and Calendar are now legacy, supplanted by the java.time classes. Much of the java.time functionality is back-ported to Android (see below).
To get the date-only value of the Java & Unix epoch reference date of 1970-01-01, use LocalDate. The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate epoch = LocalDate.ofEpochDay( 0L ) ;
epoch.toString: 1970-01-01
To get the date-time value of that same epoch, use the constant Instant.EPOCH. 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 epoch = Instant.EPOCH ;
epoch.toString(): 1970-01-01T00:00:00Z
The Z in that standard ISO 8601 output is short for Zulu and means UTC.
To get a number of years, months, days since then, use the Period class.
Period period = Period.between(
LocalDate.ofEpochDay( 0 ) ,
LocalDate.now( ZoneId.of( "America/Montreal" ) )
) ;
Search Stack Overflow for more discussion and examples of Period.
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 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 ThreeTenABP….
Consider the following snippet:
Calendar futureDate = Calendar.getInstance();
int year = 2011;
int month = 11;
int day = 14;
futureDate.set(year,month, day);
System.out.println(futureDate.toString());
java.sql.Date sqlDate = new java.sql.Date( futureDate.getTime().getTime());
The printout from futureDate.toString() is:
.....YEAR=2011,MONTH=11,WEEK_OF_YEAR=43,WEEK_OF_MONTH=4,DAY_OF_MONTH=14,DAY_OF_YEAR=289,DAY_OF_WEEK=1,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=11,HOUR_OF_DAY=11,MINUTE=32,SECOND=51,MILLISECOND=117,ZONE_OFFSET=-18000000,DST_OFFSET=3600000]
which shows that the Calendare object holds the correct date. However, after converting to sql date and storing in the database (MySQL through JDBC), the MySQL table shows '2011-12-14' for this date instead of '2011-11-14'.
I would have suspected locale and time zone, but these would cause discrepancy in the time of day not in the month part of the date.
Any clues to what I did wrong?
Calendar#set(int, int, int) interprets the month argument as zero-based, so futureDate.set(2011, 11, 14) sets the calendar's month to December.
tl;dr
LocalDate.of( 2011 , 11 , 14 ) // November 14th, 2011
Details
The Answer by Matt Ball is correct. But now there is a much improved way.
java.time
The troublesome old date-time classes such as Calendar, java.util.Date, and java.sql.Date are now legacy, supplanted by the java.time classes.
Unlike the legacy classes, the java.time classes have sane numbering, such as months being numbered 1-12 for January to December, and 1-7 for Monday to Sunday.
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate ld = LocalDate.of( 2011 , 11 , 14 ) ;
Or use the handy Month enum.
LocalDate ld = LocalDate.of( 2011 , Month.NOVEMBER , 14 ) ;
With a JDBC driver supporting JDBC 4.2 and later, you may pass your java.time objects directly to the database.
myPreparedStatement.setObject( … , ld ) ;
When fetching, use getObject.
LocalDate ld = myResultSet.getObject( … , LocalDate.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.
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.
I have one Calendar object which is as per the user's time zone which may be PST etc, now i want to convert the same to GMT and retain the time i.e. is the calendar initially was set # 00:00:00 at PST it should be converted to 08:00:00 after the conversion taking into consideration the time/date difference . Can someone provide me some help on this.
Appreciate the help in advance.
Thanks,
Vaibhav
Just create a new Calendar in GMT, set the time in that calendar to the same as the original calendar, and you're done:
gmtCalendar.setTime(userCalendar.getTime());
That should be fine, as the getTime() call returns the instant in time (i.e. a java.util.Date with no associated time zone).
As ever though, if you're doing any significant amount of date/time work in Java you should strongly consider using Joda Time instead.
tl;dr
( ( GregorianCalendar ) myCal ) // Cast from a general `Calendar` to specific subclass `GregorianCalendar`.
.toZonedDateTime() // Convert from troublesome legacy class to modern java.time class, `ZonedDateTime`.
.toInstant() // Extract a UTC-specific value, an `Instant` object.
java.time
The modern approach uses java.time classes.
Convert your legacy Calendar object (if GregorianCalendar) to a ZonedDateTime. Call new conversion methods added to the old classes.
GregorianCalendar gc = ( GregorianCalendar ) myCal ;
ZonedDateTime zdt = gc.toZonedDateTime() ;
Now extract an Instant, a value always in UTC. You can think of it this way conteptually: ZonedDateTime = ( Instant + ZoneId )
Instant instant = zdt.toInstant() ;
For more flexibility such as generating strings in various formats, convert to an OffsetDateTime object.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
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.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.
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'm trying to add some minutes to a date using plusMinutes, but it just doesn't add anything at all:
Here's the code:
String currentDate ;
SimpleDateFormat myFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date1= null;
DateTime dt;
currentDate ="27/12/2010 11:29" ;
try {
date1= myFormat.parse(currentDate);
} catch (ParseException ex) {
ex.printStackTrace();
}
dt = new DateTime(date1);
dt.plusMinutes(30);
Javadoc says
Returns a copy of this datetime plus the specified number of millis.
so
do something like
dt = new DateTime(date1);
dt = dt.plusMinutes(30);
System.out.println(""+dt);
Beauty of joda is that most of their classes are immutable like String in Java. Update operations doesn't change the original object. So plusMinutes(...) returns a new copy of the DateTime with the minutes added which you can assign to a new variable as shown below.
DateTime newDt=dt.plusMinites(30);
System.out.println(newDt);
I think you want dt = dt.plusMinutes(30);
plusMinutes returns a calculated dateTime. It does not modify the dateTime it is called on.
tl;dr
java.time.LocalDateTime.parse(
"27/12/2010 11:29" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm" )
).plusMinutes( 30 )
2010-12-27T11:59
Tip: If you intended this to be a moment, a specific point on the timeline, apply the context of a time zone (ZoneId) to get a ZonedDateTime.
java.time
Your Question uses the troublesome old date-time classes from the earliest versions of Java, and your Question uses the Joda-Time project which is now in maintenance mode. Both have been supplanted by the java.time classes built into Java 8 and later.
Your string input lacks an indicator of time zone or offset-from-UTC. So parse as a java.time.LocalDateTime.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm" ) ;
LocalDateTime ldt = LocalDateTime.parse( "27/12/2010 11:29" , f ) ;
ldt.toString(): 2010-12-27T11:29
Note that you do not have an actual moment, this is not a specific point on the timeline. This is only a vague idea about potential moments along a range of about 26-27 hours. To determine an actual moment, place this in the context of a time zone (or offset): ZonedDateTime zdt = ldt.atZone( ZoneId.of( "Pacific/Auckland" ) ) ;.
Add your minutes.
LocalDateTime later = ldt.plusMinutes( 30 ) ;
later.toString(): 2010-12-27T11:59
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, 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.