When creating a calendar object and setting the date/time using SimpleDateFormat to parse a string, is it possible to set the date and time in two separate lines of code? For example, in my SQLite db the date (mm-dd-yyyy) is stored in a separate column from the time (hh:mm). Is it kosher to do something like the following:
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdfDate = new SimpleDateFormat("MM-dd-yyyy");
SimpleDateFormat sdfTime = new SimpleDateFormat("hh:mm zzz");
cal.setTime(sdfDate.parse(DATE));
cal.setTime(sdfTime.parse(TIME));
Would the second cal.setTime line reset the date portion of the calendar object to now and just change the time?
Yes it would.
setTime() sets the the time regardless of the fact that a date contained no time value (00:00:00) or no date value (01.01.1970).
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdfDate = new SimpleDateFormat("MM-dd-yyyy hh:mm zzz");
cal.setTime(sdfDate.parse(DATE+ " " + TIME));
Should work out for you.
tl;dr
ZonedDateTime.of(
LocalDate.parse( "12-23-2015" , DateTimeFormatter.ofPattern( "MM-dd-yyyy") ) ,
LocalTime.parse( "21:43" ) ,
ZoneId.of( "Pacific/Auckland" )
)
.toString()
2015-12-23T21:43+13:00[Pacific/Auckland]
Details
The Answer by Jan is correct.
java.time
Alternatively, you could use the new date-time framework, java.time.
The java.time framework built into Java 8 and later supplants the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
If your inputs lacked an offset-from-UTC, then we could treat the date and the time-of-day separately. The new classes include LocalDate to represent a date-only value without a time-of-day, and LocalTime to represent a time-only value without a date. Then you can combine them and adjust into their intended time zone.
DateTimeFormatter formatterDate = DateTimeFormatter.ofPattern( "MM-dd-yyyy");
LocalDate localDate = LocalDate.parse( "12-23-2015" , formatterDate );
LocalTime localTime = LocalTime.parse( "21:43" );
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.of( localDate , localTime , zoneId );
But your time string does contain an offset-from-UTC. So we should take the same approach as the Answer by Jan, concatenate the pair of strings and then parse.
String input = "12-23-2015" + " " + "21:43-05:00" ;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MM-dd-yyyy HH:mmxxx");
ZonedDateTime zdt = ZonedDateTime.parse( input , formatter );
ISO 8601
By the way, in the future when serializing a date, a time, or a date-time to a string such as you did in your SQLite database I strongly recommend using the standard ISO 8601 formats: YYYY-MM-DD, HH:MM, and YYYY-MM-DDTHH:MM:SS.S±00:00. For example, 2007-12-03T10:15:30+01:00. These formats are standardized, easy for humans to read and discern, and easy for computers to parse without ambiguity.
The java.time framework parses and generates strings in these formats by default. Also, java.time extends ISO 8601 by appending the name of the time zone in square brackets. For example, 2007-12-03T10:15:30+01:00[Europe/Paris].
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.
Related
I'm simply trying to parse a string in JLabel to a date using a simpleDateFormatter(). Based On everything I've searched online, this code should work. However, I'm receiving the "cannot find symbol - method parse(java.lang.String)" error during compiliation. Any advice on how to resolve the issue would be greatly appreciated.
The JLabel in question was populated with a date from a database query using JDBC.
Additionally, I'm aware that that java.util.Date has been deprecated, but would still like to use it for this.
Code Snippet:
private Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
private JLabel dateDataLabel = new JLabel("");
private void setAndParseLabel()
{
dateDataLabel.setText(formatter.format(validatePass.eventDate));
java.util.Date aDate = formatter.parse(dateDataLabel.getText());
}
tl;dr
You are ignoring crucial issue of time zone. You are unwittingly parsing the input as a value in UTC.
You are using terrible old date-time classes that were supplanted years ago. Use java.time instead.
Example code:
LocalDateTime
.parse(
"2018-01-23 13:45".replace( " " , "T" ) // Comply with standard ISO 8601 format by replacing SPACE with `T`. Standard formats are used by default in java.time when parsing/generating strings.
) // Returns a `LocalDateTime` object. This is *not* a moment, is *not* a point on the timeline.
.atZone( // Apply a time zone to determine a moment, an actual point on the timeline.
ZoneId.of( "America/Montreal" )
) // Returns a `ZonedDateTime` object.
.toInstant() // Adjust from a time zone to UTC, if need be.
java.time
The modern approach uses the java.time classes.
Your input string is almost in standard ISO 8601 format. To fully comply, replace that SPACE in the middle with a T.
String input = "2018-01-23 13:45".replace( " " , "T" ) ;
Parse as a LocalDateTime because your input has no indicator of time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
A LocalDateTime by definition does not represent a moment, is not a point on the timeline. It represents potential moments along a range of about 26-27 hours (the range of time zones around the globe).
To determine a moment, assign a time zone (ZoneId) to get a ZonedDateTime object.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
If you wish to see that same moment through the wall-clock time of UTC, extract an Instant.
Instant instant = zdt.toInstant() ; // Adjust from some time zone to UTC.
Avoid java.util.Date where feasible. But if you must interoperate with old code not yet updated to java.time, you can convert back-and-forth. Call new conversion methods added to the old classes.
java.util.Date d = java.util.Date.from( instant ) ; // Going the other direction: `myJavaUtilDate.toInstant()`
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.
java.text.Format does not have method parse, so the code does not compile.
You can refer it by java.text.DateFormat:
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
There is no method parse in java.text.Format. Use java.text.DateFormat instead:
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
I have a String representation of a local date time, and a Java TimeZone.
I am trying to get output in the format MM/dd/yyyy HH:mm:ssZ but I can't figure out how to create a Calendar or JodaTime object with the correct date time and timezone. How do you get a TimeZone converted to a value that can be parsed by SimpleDateFormat 'Z' or 'z'?
TimeZone tz = TimeZone.getTimeZone("America/Chicago");
String startDate = "08/14/2014 15:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Calendar cal = Calendar.getInstance(tz);
cal.setTime(sdf.parse(startDate));
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ssZ");
and
sdfZ.format(cal.getTime())
returns
08/14/2014 15:00:00-0400
which is EST.
Is the only workaround to create a Calendar or Joda DateTime and set the individual year/month/day/hour/min values by parsing the string "08/14/2014 15:00:00" ?
Calendar getTime() - Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch(01-01-1970 00:00 GMT)") irrespective of which timezone you are displaying. But hour of day in different TimeZone will be different. get(Calendar.HOUR_OF_DAY)
You should try
sdfZ.setTimeZone(tz);
tl;dr
ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "America/Chicago" ) ) ;
String output = zdt.toInstant().toString() ;
2016-12-03T10:15:30Z
java.time
Both the java.util.Calendar class and the Joda-Time library have been supplanted by the java.time classes.
Instant
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = Instant.now();
Call toString to generate a String in standard ISO 8601 format. For example, 2011-12-03T10:15:30Z. This format is good for serializing date-time values for data storage or exchange.
String output = instant.toString(); // Ex: 2011-12-03T10:15:30Z
Time zone
Assign a time zone.
ZoneId z = ZoneId.of( "America/Chicago" );
ZonedDateTime zdt = instant.atZone( z );
As a shortcut, you can skip over using Instant.
ZonedDateTime zdt = ZonedDateTime.now( z );
Calling toString on ZonedDateTime gets you an extended version of standard ISO 8601 format where the name of the time zone is appended in square brackets. For example, 2007-12-03T10:15:30+01:00[Europe/Paris].
String output = zdt.toString(); // Ex: 2007-12-03T10:15:30+01:00[Europe/Paris]
DateTimeFormatter
The DateTimeFormatter class has a predefined formatter constant for your desired output: DateTimeFormatter.ISO_LOCAL_DATE_TIME
String output zdt.format( DateTimeFormatter.ISO_LOCAL_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.
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.
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")?
for example, 2012-10-30T22:30:00+0300 need to be shown in 2012-10-30T22:30:00-0600 (the local time for example)
need to implement in java (android app)
how can I manage doing that?
That's what a Date is: a universal instant in time. Choose the appropriate time zone when displaying it, and you'll have the time string you want:
Date now = new Date();
DateFormat df = df.getDateTimeInstance();
System.out.println(df.format(now)); // now, displayed in the current time zone (examle: Germany)
df.setTimeZone(theLondonTimeZone);
System.out.println(df.format(now)); // now, displayed in the time zone of London
tl;dr
OffsetDateTime
.parse(
"2012-10-30T22:30:00+0300" ,
DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ssX" )
)
.toInstant()
.atZone(
ZoneId.of( "Europe/London" )
)
.toString()
2012-10-30T19:30Z[Europe/London]
java.time
The modern solution uses the java.time classes.
Define a formatter to match your input.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ssX" ) ;
Parse the input as a OffsetDateTime.
String input = "2012-11-05T13:00:00+0200" ;
OffsetDateTime odt = OffsetDateTime.parse( input , f );
odt.toString(): 2012-11-05T13:00+02:00
Tip: Always include the COLON character as a delimiter between the hours and minutes of the offset. We could then skip the custom formatting pattern: OffsetDateTime.parse( "2012-11-05T13:00+02:00" ).
Adjust to UTC, an offset of zero hours-minutes-seconds, by extracting a Instant object.
Instant instant = odt.toInstant() ;
In standard ISO 8601 format, the Z on the end means UTC (offset of zero). Pronounced “Zulu”.
instant.toString(): 2012-11-05T11:00:00Z
Adjust into London time.
ZoneId zLondon = ZoneId.of( "Europe/London" ) ;
ZonedDateTime zdtLondon = instant.atZone( zLondon ) ;
zdtLondon.toString(): 2012-11-05T11:00Z[Europe/London]
Adjust to another time zone.
ZoneId zMontreal = ZoneId.of( "America/Montreal" );
ZonedDateTime zdtMontreal = instant.atZone( zMontreal );
zdtMontreal.toString(): 2012-11-05T06:00-05:00[America/Montreal]
All these objects (odt, instant, zdtLondon, and zdtMontreal) represent the very same simultaneous moment, the same point on the timeline. Same moment, different wall-clock 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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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. Hibernate 5 & JPA 2.2 support java.time.
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….
https://i.stack.imgur.com/eKgbN.png
Table of which java.time library to use with which version of Java or Android
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 joda time library solved my problem optimally, using dateTime & dateTime zone like following:
DateTimeFormatter parser2 = ISODateTimeFormat.dateTimeNoMillis();
DateTime dt = new DateTime();
DateTime dt2 = new DateTime();
dt = DateTime.parse("2012-11-05T13:00:00+0200");
System.out.println(dt.toString());
dt2 = DateTime.parse("2012-11-05T21:45:00-08:00");
DateTimeZone dtz = dt2.getZone();
System.out.println(dt.withZone(dtz).toString());
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.