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
Related
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.
I have a date picker field on my JSP page. While selecting that field, the date is displayed in Japanese format (2013年11月24日) in my text field. Now, while reading that date field in my controller, I am getting this value 2013年11月24日.
How can I convert this date format into normal date format?
It seems the format you've given is the default date format of the Japanese locale, so you can use the build in facility:
DateFormat df = DateFormat.getDateInstance(DateFormat.FULL, new Locale("ja"));
Javadoc: http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html
IDEONE example: http://ideone.com/0W7szq
DateFormat df = DateFormat.getDateInstance(DateFormat.FULL, new Locale("ja"));
System.out.println(df.format(new Date()));
System.out.println(df.parse("2013年11月24日"));
Output:
2013年11月24日
Sun Nov 24 00:00:00 GMT 2013
Edit:
Please note that this DateFormat class is not thread-safe, so you cannot make the instant static. If you do not want to create the instance again and again like above, you may want to look into the thread-safe variant in Joda time: DateTimeFormat.
The Answer by billc.cn is correct but outdated. The troublesome old date-time classes are now legacy, supplanted by the java.time classes.
java.time
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL );
f = f.withLocale( Locale.forLanguageTag("ja") ) ;
String input = "2013年11月24日" ;
LocalDate ld = LocalDate.parse( input , f );
input: 2013年11月24日
ld.toString(): 2013-11-24
See live code in IdeOne.com.
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 );
You should be using LocalDate objects to hold your date-only values in your business logic and data model. Generate the strings only as needed for presentation such as display in your JSP page.
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.
Are the delimiters always the same?
If so, can't you just use SimpleDateFormat("yyyy年MM月dd")?
Given Week of the year, the week day and the year, how can we get the Date in Java?
With Jodatime, I tried the following:
DateTime dt = new DateTime();
dt.withYear(year);
dt.withWeekOfWeekyear(weekOfYear);
dt.withDayOfWeek(weekDay);
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyMMdd");
System.out.println(dateTimeFormatter.print(dt));
But it gets the current Date!
JodaTime returns a changed copy, so do:
DateTime dt = new DateTime()
.withWeekyear(year)
.withWeekOfWeekyear(weekOfYear)
.withDayOfWeek(weekDay);
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyMMdd");
System.out.println(dateTimeFormatter.print(dt));
And this should work as expected.
The accepted answer has bug..withYear(year) should be withWeekyear(year). #Neet please update it.
You need to reassign the date afterwards!
the dt.with*() methods simply make a copy of the date.
try
DateTime dt = new DateTime();
dt = dt.withYear(year);
dt = dt.withWeekOfWeekyear(weekOfYear);
dt = dt.withDayOfWeek(weekDay);
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyMMdd");
System.out.println(dateTimeFormatter.print(dt));
We can also use this native java code using Calendar class:
SimpleDateFormat sdf = new SimpleDateFormat("MM dd yyyy");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.WEEK_OF_YEAR, 23);
cal.set(Calendar.DAY_OF_WEEK, 3);
cal.set(Calendar.YEAR,2013);
System.out.println(sdf.format(cal.getTime()));
Here is a simple example of how to do it without JodaTime:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Snippet {
public static void main(String args[]) {
String year = "2013";
String week_of_year = "46";
String day_of_week = "4";
String yearweekday = year + week_of_year + day_of_week;
SimpleDateFormat sdf = new SimpleDateFormat("yyyywwu");
Date date = null;
try {
date = sdf.parse(yearweekday);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(date);
}
}
Good luck!
tl;dr
YearWeek.of( 2017 , 1 )
.atDay( DayOfWeek.TUESDAY )
.format( DateTimeFormatter.ofPattern( "uuMMdd" ) )
“Week” ambiguous
The word 'week' is ambiguous. Do you mean week number 1 contains January 1? Or week number 1 contains the first of a particular day of year such as Sunday or Monday?
Or do you mean a standard ISO 8601 week? To quote from YearWeek doc:
ISO-8601 defines the week as always starting with Monday. The first week is the week which contains the first Thursday of the calendar year. As such, the week-based-year used in this class does not align with the calendar year.
java.time
The modern approach uses the java.time classes.
The troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes.
The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
ThreeTen-Extra
The ThreeTen-Extra project extends java.time with additional functionality. This includes a handy YearWeek class, just what we need for this Question.
Specify your week-based year number and your week number.
YearWeek yw = YearWeek.of( 2017 , 1 ) ;
The LocalDate class represents a date-only value without time-of-day and without time zone.
You can ask the YearWeek object to determine the date of a day contained within its week. Specify a DayOfWeek enum object. Note that a DayOfWeek is an object rather than a mere integer or string, providing for type-safety and valid values.
LocalDate ld = yw.atDay( DayOfWeek.TUESDAY ) ;
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.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:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Test
int weekNumber = 34;
int year = 2021;
System.out.println(getLocalDate(weekNumber, DayOfWeek.TUESDAY, year, Locale.UK));
System.out.println(getLocalDate(weekNumber, DayOfWeek.TUESDAY, year, Locale.US));
System.out.println(getLocalDate(weekNumber, DayOfWeek.SUNDAY, year, Locale.UK));
System.out.println(getLocalDate(weekNumber, DayOfWeek.SUNDAY, year, Locale.US));
}
static LocalDate getLocalDate(int weekNumber, DayOfWeek dow, int year, Locale locale) {
return LocalDate.of(year, 2, 1)
.with(dow)
.with(WeekFields.of(locale).weekOfWeekBasedYear(), weekNumber);
}
}
Output:
2021-08-24
2021-08-17
2021-08-29
2021-08-15
ONLINE DEMO
Note that the first day of the week is Locale-dependent e.g. it is Monday in the UK while Sunday in the US. As per the ISO 8601 standards, it is Monday. For comparison, check the US calendar and the UK calendar. Accordingly, the date will vary as shown in the example above.
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.
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….
What SimpleDateFormat to use for parsing Oracle date ?
I'm using this SimpleDateFormat.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/mm/dd hh:mm:ss.sss");
its giving this exception.
java.text.ParseException: Unparseable date: "2011-08-19 06:11:03.0"
Kindly please tell me the SimpleDateFormat to use. Thanks.
You should use this Pattern "yyyy-MM-dd HH:mm:ss.S" instead of "yyyy/mm/dd hh:mm:ss.sss".
little h for "Hour in am/pm (1-12)" and H for "Hour in day (0-23)"
see here: SimpleDateFormat
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
Date date = dateFormat.parse("2011-08-19 06:11:03.0");
tl;dr
LocalDateTime.parse(
"2011-08-19 06:11:03.0".replace( " " , "T" )
)
Details
Your input string does not match your formatting pattern. Your pattern has slash characters where your data has hyphens.
java.time
Furthermore, you are using terrible old date-time classes that are now legacy, supplanted by the java.time classes.
Your input string nearly complies with the ISO 8601 standard for date-time formats. Replace the SPACE in the middle with a T.
String input = "2011-08-19 06:11:03.0".replace( " " , "T" ) ;
Your input lacks any indicator of time zone or offset-from-UTC. So we parse as a LocalDateTime, for an object lacking any concept of zone/offset.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
To generate a string in standard format, call toString.
String output = ldt.toString() ;
If this input was intended for a specific time zone, assign it.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
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.