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.
Related
im creating a date from weeknumber, and a day of the week only. this I have successfully done with SimpleDateFormat, but i want to save it as jodatime, i have tried many things, but nothing that really worked.
This is my code so far.
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.WEEK_OF_YEAR, week_of_year);
cal.set(Calendar.DAY_OF_WEEK, day_of_week);
sdf.format(cal.getTime());
DateTimeFormatter dtf = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
DateTime jodatime = dtf.parseDateTime(sdf.toString());
I would like to get a jodatime så that my calendar kan sort objects based on the date, the time inst necessary.
When I run the code and want to display the jodatime, I get this error:
java.lang.IllegalArgumentException: Invalid format: "java.text.SimpleDateFormat#b93b42a0"
at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:945)
at com.example.casper.autimeplan.Fragments.ScheduleFragment$MyJavaScriptInterface.getBasicInfo(ScheduleFragment.java:282)
at com.example.casper.autimeplan.Fragments.ScheduleFragment$MyJavaScriptInterface.access$400(ScheduleFragment.java:186)
at com.example.casper.autimeplan.Fragments.ScheduleFragment$MyJavaScriptInterface$1.run(ScheduleFragment.java:203)
tl;dr
LocalDate.now().with( WeekFields.ISO.weekOfWeekBasedYear(), weekOfYear )
.with( WeekFields.ISO.dayOfWeek(), dayOfWeek )
java.time
Do not use the troublesome old date-time classes. Also, the Joda-Time project, now in maintenance mode, advises migration to the java.time classes. For Android, see the ThreeTenABP project mentioned in last bullets below.
You have not defined what you mean by week number. There are many ways to define a week of year. I will assume you meant the standard ISO 8601 definition of week # 1 having the first Thursday of the calendar, and Monday being the first day of every week.
Use the WeekFields class, specifically the WeekFields.ISO object.
long weekOfYear = 27 ; // 1-52 or 1-53 for ISO 8601 week-based years.
long dayOfWeek = 2 ; // 1-7 for Monday-Sunday, per ISO 8601 standard.
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) ) ;
LocalDate adjusted = today.with( WeekFields.ISO.weekOfWeekBasedYear(), weekOfYear )
.with( WeekFields.ISO.dayOfWeek(), dayOfWeek ) ;
Dump to console.
System.out.println( "2017-W27-02: " + adjusted ) ;
2017-W27-02: 2017-07-04
See this code run live at IdeOne.com.
By the way… While not back-ported to older Android, other Java platforms can use the nifty YearWeek class in the ThreeTen-Extra library for this kind of work.
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….
You are simply passing toString of object which won't work.
try something like this
private static String parseDateTime(String input){
String pattern = "MM/dd/yyyy HH:mm:ss";
DateTime dateTime = DateTime.parse(input, DateTimeFormat.forPattern(pattern));
return dateTime.toString("MM/dd/yyyy HH:mm:ss");
}
Read more here
I have CSV data to import into data base where I have date column in that CSV in that some dates are like 1-DEC-16 without a leading zero (padding zero). How to make that String as 01-DEC-2016? Can it be done with SimpleDateFormat or is there any String format method? I tried with below but it’s not happening.
String d="1-DEC-17";
String newstring = new SimpleDateFormat("yyyy-MM-dd").format(d);
System.out.println(newstring);
d vs dd
To parse a string with a leading zero on the month or day-of-month, use a pair of formatting pattern characters. That would be dd for day-of-month.
To parse a string without a leading zero, use a single character, d for day-of-month.
Unfortunately, your input has the month name abbreviation in all uppercase. That violates the norm of the English-speaking locales I know of, such as Locale.US. So by default, a DateTimeFormatter will refuse to process that improper input. To tolerate the all-uppercase, we can set the formatter to be “lenient”.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "d-MMM-uu" , Locale.US ).withResolverStyle( ResolverStyle.LENIENT ) ;
LocalDate ld = LocalDate.parse( "1-DEC-17" , f ) ;
See this code run live at IdeOne.com.
ld.toString(): 2017-12-01
If sending this value to a database, do not use a string for date-time value. Use a date-time object for date-time values.
For JDBC drivers compliant with JDBC 4.2 and later, pass the java.time types directly via setObject & getObject.
myPreparedStatement.setObject( … , ld ) ;
If not compliant, convert briefly to the troublesome old legacy type, java.sql.Date. Use the new methods added to the old classes.
java.sql.Date d = java.sql.Date.valueOf( ld ) ;
myPreparedStatement.setDate( … , d ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Using new Java 8 java.time API, I need to convert LocalDate and get full name of month and day. Like March (not Mar), and Monday (not Mon). Friday the 13th March should be formatted like Friday, 13 March.. not Fri, 13 Mar.
The string you are looking for is MMMM.
Source: DateTimeFormatter Javadoc
tl;dr
Use automatic localization. No need to specify formatting pattern.
localDate.format(
DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL )
.withLocale( Locale.UK )
)
Monday, 23 January 2017
LocalDate
.of( 2017 , Month.JANUARY , 23 )
.getMonth()
.getDisplayName(
TextStyle.FULL ,
Locale.CANADA_FRENCH
)
janvier
Month
Taking your title literally, I would use the handy Month enum.
LocalDate ld = LocalDate.of( 2017 , Month.JANUARY , 23 );
Month month = ld.getMonth() ; // Returns a `Month` object, whereas `getMonthValue` returns an integer month number (1-12).
Let java.time do the work of automatically localizing. To localize, specify:
TextStyle to determine how long or abbreviated should the string be.
Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
For example:
String output = month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ; // Or Locale.US, Locale.KOREA, etc.
janvier
Date
If you want the entire date localized, let DateTimeFormatter do the work. Here we use FormatStyle rather than TextStyle.
Example:
Locale l = Locale.CANADA_FRENCH ; // Or Locale.US, Locale.KOREA, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL )
.withLocale( l ) ;
String output = ld.format( f );
dimanche 23 janvier 2107
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.
Yes. Now it can be done.
LocalDate dd = new LocalDate(); //pass in a date value or params(yyyy,mm)
String ss = dd.monthOfYear.getAsText(); // will give the full name of the month
String sh = dd.monthOfYear.getAsShortText(); // shortform
import java.time.LocalDate;
Just use the getDayOfWeek()
LocalDate.of(year, month, day).getDayOfWeek().name()
You can use it as
public static String dayName(int month, int day, int year) {
return LocalDate.of(year, month, day).getDayOfWeek().name();
}
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 have a String in format "YYYY-MM-dd" and i want convert this into "MMM dd, yyyy" format.
I used bellow code to do this;
But when i convert "2014-11-18" the output is this "Sun Dec 29 00:00:00 IST 2013"
How can I solve this?
DateFormat target=new SimpleDateFormat("MMM dd, yyyy");
String P_date="2014-11-18"
Date test1 = new SimpleDateFormat("YYYY-MM-dd").parse(P_date);
String converted_date=target.format(test1);
Date test=target.parse(converted_date);
The y (lowercase Y) format means "year". Y (uppercase Y) you were using means "WeekYear".
Just use y and you should be OK:
DateFormat target=new SimpleDateFormat("MMM dd, yyyy");
String P_date="2014-11-18";
Date test1 = new SimpleDateFormat("yyyy-MM-dd").parse(P_date);
String converted_date=target.format(test1);
Date test=target.parse(converted_date);
Y returns Week year that's why you are seeing week day too. use y instead.
Date test1 = new SimpleDateFormat("yyyy-MM-dd").parse(P_date);
You can write like this
final JDateChooser startDateChooser = new JDateChooser();
startDateChooser.setDateFormatString("yyyy-MM-dd");
Date startDate = startDateChooser.getDate();
HashMap listMap = new HashMap();
listMap.put("Start Period is ", ((startDate.getYear() + 1900)+ "-" + (startDate.getMonth() + 1) + "-" +startDate.getDate()));
tl;dr
LocalDate.parse( "2014-11-18" ).format( // Parse string as `LocalDate` object, then generate a string in a certain format.
DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM )
.withLocale( Locale.US ) // Automatically localize to a locale’s human language and cultural norms.
) // Returns a String.
Details
The accepted Answer by Mureinik is correct, your formatting pattern used codes incorrectly.
Another issue is that you are interested in a date-only value, but you are using a date-with-time type.
Also, you are using troublesome old date-time classes that are now supplanted by the java.time classes.
java.time
Your YYYY-MM-DD format complies with ISO 8601 format. The java.time classes use those standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate ld = LocalDate.parse( "2014-11-18" ) ;
To generate a string in other formats, use the DateTimeFormatter or DateTimeFormatterBuilder classes.
You could specify a hard-coded formatting pattern. But better to soft-code by letting java.time automatically localize. To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Example:
Locale l = Locale.US ; // Or Locale.CANADA_FRENCH, Locale.ITALY, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( l );
String output = zdt.format( f );
Nov 18, 2014
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.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or 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.