Java SWT DateTime: Determine day of Week - java

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.

Related

Date compare java fail

while comparing future days it occurs some fail in Java. Look at the code if you can
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
Date date = dateFormat.parse("2258-11-01");
Date date1 = dateFormat.parse("2258-10-31");
System.out.println(date.after(date1));
Output is:false
Anyone has idea why it does't work?
The m format represents a minute in the hour. You probably meant to use M, representing the month in the year:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
You should use the capital MM for month, overwise it does not parse like you want it to.
new SimpleDateFormat("yyyy-MM-dd");
tl;dr
Use the modern java.time classes to parse your strings that happen to be in standard format.
LocalDate.parse( "2258-11-01" )
.isAfter(
LocalDate.parse( "2258-10-31" )
)
true
Details
As others mentioned, the formatting pattern is case-sensitive, and yours is incorrect.
Another problem, you are inappropriately squeezing a date-only value into a type intended for a date with time-of-day in UTC.
Also, you are using the terrible old date-time classes that were supplanted years ago by the modern java.time classes.
Your input strings happen to comply with the excellent ISO 8601 standard. The java.time classes use these formats by default when parsing/generating strings. So no need to even bother with defining a formatting pattern.
LocalDate ld1 = LocalDate.parse( "2258-11-01" ) ;
LocalDate ld2 = LocalDate.parse( "2258-10-31" ) ;
Compare.
boolean isAfter = ld1.isAfter( ld2 ) ; // true
All this has been covered many many times already on Stack Overflow. Please learn to search Stack Overflow thoroughly before posting.
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.

Joda-Time Formatting for Islamic Date

I am using Joda-Time to get the Islamic date in the dd MMMM yyyy but I am always getting dd MM yyyy.
Any advise? could it be that Hijri dates are not supported for formatting? It's not clear on the Joda-Time website.
DateTime dtISO = new DateTime(2014,2,25,0,0,0,0);
DateTime dtIslamic = dtISO.withChronology(IslamicChronology.getInstance());
String formatIslamic= "dd MMMM yyyy";
DateTimeFormatter formatter = DateTimeFormat.forPattern(formatIslamic).withChronology( IslamicChronology.getInstance());
String islamicDateString = formatter.print(dtIslamic);
This is currently not implemented. The BasicChronology class sets the monthOfYear field to use GJMonthOfYearDateTimeField which in turn gets it's data from java.text.DateFormatSymbols. The IslamicChronology uses a sets the monthOfYear field to a BasicMonthOfYearDateTimeField which has the following implementation of getAsText:
public String getAsText(int fieldValue, Locale locale) {
return Integer.toString(fieldValue);
}
What someone needs to do is to create a IslamicMonthOfYearDateTimeField that extends BasicMonthOfYearDateTimeField and overrides the method so that it returns the name of the month rather than the numeric value of the month. This could either be done in the joda-time codebase, or completely outside. To get this working outside of joda, just extend IslamicChronology and override assemble to pull in your new IslamicMonthOfYearDateTimeField. I'd issue a pull request to joda-time myself, but I doubt they'd accept a non-localized solution.
tl;dr
java.time.chrono.HijrahDate.from(
LocalDate.of( 2014 , 2 , 25 )
)
.get( ChronoField.YEAR )
1435
java.time
The Joda-Time project is now in maintenance mode, advising migration to the java.time classes.
The java.time classes offer a HijrahChronology and HijrahDate in the java.time.chrono package.
For Java 6 & 7, and for earlier Android, the ThreeTen-Backport project also offers a HijrahChronology and HijrahDate.
LocalDate ld = LocalDate.of( 2014 , 2 , 25 ) ;
HijrahDate hd = HijrahDate.from( ld );
String output = hd.toString() ;
output: Hijrah-umalqura AH 1435-04-25
As for other formats, the format method with DateTimeFormatter seem to revert to ISO chronology.
Locale locale = Locale.forLanguageTag( "en-US-u-ca-islamic-umalqura" );
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL ).withLocale( locale );
String output2 = hd.format( f );
output2: Tuesday, February 25, 2014
While I do not have time at the moment to do so, I suggest looking at the source code of the HijrahDate::toString method.
You can roll-your-own formatting by using the example code as seen in the java.time.chrono package documentation.
int day = hd.get( ChronoField.DAY_OF_MONTH );
int dow = hd.get( ChronoField.DAY_OF_WEEK );
int month = hd.get( ChronoField.MONTH_OF_YEAR );
int year = hd.get( ChronoField.YEAR );
System.out.printf( "%s %s %d-%s-%d%n" , hd.getChronology().getId() , dow , day , month , year );
Hijrah-umalqura 2 25-4-1435
See also:
Convert Jalali calendar to Georgian in java
Get a gregorian date from Hijri date strings
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.

java.util.Date to java.sql.Date conversion gives wrong month

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.

Java Calendar timezone converting to GMT problem

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.

Ask Gregorian Calendar for hour of day in java

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.

Categories