Oracle date to Java date - java

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.

Related

how to convert String ("1-DEC-16") and ("01-DEC-16") to java Date as 01-DEC-2016

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.

Java Calendar object, setting date and time separately

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.

Error when converting date format to another

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.

Java date is not preserving milliseconds in conversion with simple date format

I'm trying to convert the following string "2012-04-13 04:08:42.794" to a date type:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
Date convertedDate;
try {
convertedDate = dateFormat.parse(dateString);
System.out.println(" in utils: "+convertedDate.toString());
} catch (ParseException e) {
e.printStackTrace();
return null;
}
//----------------- i think this is the problem
java.sql.Date sqlDate = new java.sql.Date(convertedDate.getTime());
System.out.println("sql: "+sqlDate.toString());
return sqlDate;
But this is printing the following:
in utils: Fri Apr 13 04:08:42 PDT 2012
How can I get this date to preserve the milliseconds?
The convertedDate object does in fact contain the millisecond information. The issue here is that the toString() method format does not print milliseconds.
Do
System.out.println(" in utils: " + dateFormat.format(convertedDate));
You can also check if the ms are set with
System.out.println("millis: " + convertedDate.getTime());
He's my go at it (trying to keep the same code style as yours) :
import java.util.*;
import java.text.*;
public class main {
public static void main(String[] args)throws Exception {
long yourmilliseconds = 1119193190;
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm:ss.SSS");
Date resultdate = new Date(yourmilliseconds);
System.out.println(sdf.format(resultdate)); }
}
Output :
Jan 13,1970 17:53:13.190
Regards, Erwald
Instead of printing using toString() you can make your own printing method, so it prints the information you want specifically. Also note that most of the Date class is deprecated - look at http://docs.oracle.com/javase/6/docs/api/java/util/Date.html
Calendar now = Calendar.getInstance();
System.out.println("Current milliseconds since Jan 1, 1970 are :"
+ now.getTimeInMillis());
just use java.util.Calendar http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
tl;dr
myPreparedStatetment.setObject(
… ,
LocalDateTime.parse(
"2012-04-13 04:08:42.794".replace( " " , "T" )
)
)
Details
The Answer by SJuan76 is correct: You are being fooled by the poorly-designed output of the Date::toString method. Instead, use java.time classes.
java.time
The modern approach uses the java.time classes that supplanted the troublesome old date-time classes such as Date/Calendar.
First convert your input string to fully comply with the ISO 8601 standard. Replace the SPACE in the middle with a T.
String input = "2012-04-13 04:08:42.794".replace( " " , "T" ) ;
Parse as a LocalDateTime since your input lacks an indicator of offset-from-UTC or time zone.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
ldt.toString(): 2012-04-13T04:08:42.794
SQL
Avoid the date-time related java.sql classes. They too are supplanted by the java.time classes. As of JDBC 4.2, you can directly exchange java.time objects with your database. So you can forget all about the java.sql.Date class and its terrible hacked design.
myPreparedStatement.setObject( … , ldt ) ;
And…
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
Morals
Moral of the story # 1: Use smart objects, not dumb strings.
Moral of the story # 2: Use only java.time objects. Avoid legacy date-time classes.
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.

Problem adding minutes with plusMinutes

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.

Categories