Converting string to date format (yyyy/MM/dd) in JAVA - java

I am facing an issue when I convert my string to date format.
This is what I have tried -
First try:
String completionDate1 = request.getParameter("completion_date");
System.out.println(completionDate1); // O/P --> 21/10/2016 (Correct)
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
date = df.parse(completionDate1);
System.out.println(date); // O/P --> Tue Apr 08 00:00:00 IST 27 (Inorrect)
Second try:
String completionDate1 = request.getParameter("completion_date");
System.out.println(completionDate1); // O/P --> 21/10/2016 (Correct)
Date completionDate = new SimpleDateFormat("yyyy/MM/dd").parse(completionDate1);
System.out.println(completionDate); // O/P --> Tue Apr 08 00:00:00 IST 27 (Inorrect)
The output I'm expecting is that, the completionDate should be Date format not String. I'm just printing the completionDate just to make sure the date format is getting getting converted.
The main intention of getting it in date format is I need this for an Update query so it has to be Date and not String.
Kindly let me know where I'm going wrong. I need this date format as I need to store this date in a database.
Thanks

You have to format the date after parsing it but your parsing format is also incorrect so its giving wrong output. Try
String completionDate1 = "21/10/2016";
System.out.println(completionDate1);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
date = df.parse(completionDate1);
DateFormat df1 = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(df1.format(date));
DEMO

Wrong pattern
First problem is that your defined parsing pattern does not match your input string. For 21/10/2016 pattern should be dd/MM/yyyy.
java.sql.Date versus java.util.Date
Second problem is that for database access you should be using the java.sql.Date class for a date-only value without time-of-day and without time zone. Not to be confused with java.util.Date which is a date and time-of-day value. You should specify the fully-qualified class name in such discussions as this Question.
Neither of these classes have a “format”. They have their own internal representation, a count from epoch.
java.time
Third problem is that you are using old outdated classes. In Java 8 and later, use java.time framework now built-in. In Java 6 & 7, use its back-port, the ThreeTen-Backport project. For Android, use the adaptation of that back-port, ThreeTenABP.
In the java.time classes we now have the LocalDate class for date-only values.
String input = "21/10/2016"
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy" );
LocalDate localDate = LocalDate.parse( input , formatter );
Hopefully some day JDBC drivers will be updated to directly use the java.time types. Until then, use the new methods added to the old java.sql types to convert.
java.sql.Date sqlDate = java.sql.Date.valueOf( localDate );
Now pass that java.sql.Date object to the setDate method on a PreparedStatement object for transmission to a database.
Note that at no time did we make use of any more strings. We went from original input String to java.time.Date to java.sql.Date.
At no point did we use java.util.Date. Check your import statements to eliminate java.util.Date.
By the way, to go the other direction from java.sql.Date to LocalDate:
LocalDate localDate = mySqlDate.toLocalDate();

Use below code
String completionDate1 = request.getParameter("completion_date");
System.out.println(completionDate1); // O/P --> 21/10/2016 (Correct)
Date completionDate = new SimpleDateFormat("dd/MM/yyyy").parse(completionDate1);
String date = new SimpleDateFormat("yyyy/MM/dd").format(completionDate);
System.out.println(date);

You can try this
DateFormat df = new SimpleDateFormat("yyyy/mm/dd");
String completionDate = df.format(request.getParameter("completion_date"));
System.out.println(completionDate);

Related

Date value converted from Calendar outputs different format than String [duplicate]

I have the following scenario :
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.parse("31/05/2011"));
gives an output
Tue May 31 00:00:00 SGT 2011
but I want the output to be
31/05/2011
I need to use parse here because the dates need to be sorted as Dates and not as String.
Any ideas ??
How about:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")));
> 31/05/2011
You need to go through SimpleDateFormat.format in order to format the date as a string.
Here's an example that goes from String -> Date -> String.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("31/05/2011");
System.out.println(dateFormat.format(date)); // prints 31/05/2011
// ^^^^^^
Use the SimpleDateFormat.format
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String sDate= sdf.format(date);
You can use simple date format in Java using the code below
SimpleDateFormat simpledatafo = new SimpleDateFormat("dd/MM/yyyy");
Date newDate = new Date();
String expectedDate= simpledatafo.format(newDate);
It makes no sense, but:
System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")))
SimpleDateFormat.parse() = // parse Date from String
SimpleDateFormat.format() = // format Date into String
If you want to simply output a date, just use the following:
System.out.printf("Date: %1$te/%1$tm/%1$tY at %1$tH:%1$tM:%1$tS%n", new Date());
As seen here. Or if you want to get the value into a String (for SQL building, for example) you can use:
String formattedDate = String.format("%1$te/%1$tm/%1$tY", new Date());
You can also customize your output by following the Java API on Date/Time conversions.
java.time
Here’s the modern answer.
DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
DateTimeFormatter displayFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.forLanguageTag("zh-SG"));
String dateString = "31/05/2011";
LocalDate date = LocalDate.parse(dateString, sourceFormatter);
System.out.println(date.format(displayFormatter));
Output from this snippet is:
31/05/11
See if you can live with the 2-digit year. Or use FormatStyle.MEDIUM to obtain 2011年5月31日. I recommend you use Java’s built-in date and time formats when you can. It’s easier and lends itself very well to internationalization.
If you need the exact format you gave, just use the source formatter as display formatter too:
System.out.println(date.format(sourceFormatter));
31/05/2011
I recommend you don’t use SimpleDateFormat. It’s notoriously troublesome and long outdated. Instead I use java.time, the modern Java date and time API.
To obtain a specific format you need to format the parsed date back into a string. Netiher an old-fashioned Date nor a modern LocalDatecan have a format in it.
Link: Oracle tutorial: Date Time explaining how to use java.time.
You already has this (that's what you entered) parse will parse a date into a giving format and print the full date object (toString).
This will help you.
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
print (df.format(new Date());
I had something like this, my suggestion would be to use java for things like this, don't put in boilerplate code
This looks more compact. Finishes in a single line.
import org.apache.commons.lang3.time.DateFormatUtils;
System.out.println(DateFormatUtils.format(newDate, "yyyy-MM-dd HH:mm:ss"));

Conversion to java.sql.Date

I have a String as below which needs to be converted into java.sql.Date format:
2017-08-31 01:40:00+00:00
I am using below code and I can see date is only parsed as 2017-08-31 and not the entire string as above. Can someone please suggest?
java.util.Date utilDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(dateTimeStamp);
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
Based on the suggestion in the answers, I implemented below:
String dateTimeStamp = "2017-08-31 01:40:00+00:00";
java.text.DateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ssZZ");
java.util.Date date = format.parse(dateTimeStamp);
java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
System.out.println("timestamp - " + timestamp);
But, am getting below error:
java.text.ParseException: Unparseable date: "2017-08-31 01:40:00+00:00"
at java.text.DateFormat.parse(DateFormat.java:366)
at com.eneco.mysqlsink.WeatherForecastSink.WeatherForecastTask.put(WeatherForecastTask.java:94)
at org.apache.kafka.connect.runtime.WorkerSinkTask.deliverMessages(WorkerSinkTask.java:435)
at org.apache.kafka.connect.runtime.WorkerSinkTask.poll(WorkerSinkTask.java:251)
at org.apache.kafka.connect.runtime.WorkerSinkTask.iteration(WorkerSinkTask.java:180)
at org.apache.kafka.connect.runtime.WorkerSinkTask.execute(WorkerSinkTask.java:148)
at org.apache.kafka.connect.runtime.WorkerTask.doRun(WorkerTask.java:146)
at org.apache.kafka.connect.runtime.WorkerTask.run(WorkerTask.java:190)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
java.sql.Date only provides the date.. You need to use java.sql.Timestamp to get both date and time.
java.text.DateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
java.util.Date date = format.parse("2017-08-31 01:40:00+00:00");
java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
System.out.println(timestamp);
You're using the hh pattern, which corresponds to hour-of-am-pm field (values from 1 to 12). As the input doesn't have AM/PM designator, this won't always work as expected. You must change it to HH (hour-of-day, with values from 0 to 23).
Also, to parse the offset +00:00 you need to use the X pattern:
String input = "2017-08-31 01:40:00+00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssX");
// java.util.Date
Date date = sdf.parse(input);
The X pattern was introduced in Java 7. If you're using an older version, you can also set the UTC timezone in the formatter:
// "X" is not supported
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// set UTC in the formatter
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
// java.util.Date
Date date = sdf.parse(input);
This is worse because you need to know the offset from the input and set it in the formatter. So it's better to use X if supported.
Then you can create the sql dates from the java.util.Date:
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
java.sql.Timestamp timestamp = new Timestamp(date.getTime());
But remind that if you just System.out.println the sql date or the timestamp, those will be converted to the JVM default timezone (giving you the impression that it's wrong: see this article for more details).
Also, keep in mind that a java.sql.Date just keeps the date fields (day/month/year), setting the hours to zero (so the 01:40 is lost). A java.sql.Timestamp, on the other hand, preserves the whole UTC millis value.
Java new Date/Time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java 6 or 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, you'll also need the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.
First you parse the input to an OffsetDateTime, using a DateTimeFormatter to specify the format:
String input = "2017-08-31 01:40:00+00:00";
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssXXX");
OffsetDateTime odt = OffsetDateTime.parse(input, fmt);
Then you can convert it to sql types. In Java 8, there are built-in methods to do it:
java.sql.Date sqlDate = java.sql.Date.valueOf(odt.toLocalDate());
java.sql.Timestamp sqlTimestamp = java.sql.Timestamp.from(odt.toInstant());
In Java 7, the ThreeTen Backport has the org.threeten.bp.DateTimeUtils class:
java.sql.Date sqlDate = DateTimeUtils.toSqlDate(odt.toLocalDate());
java.sql.Timestamp sqlTimestamp = DateTimeUtils.toSqlTimestamp(odt.toInstant());
You need to include timezone identifier in your format
java.util.Date utilDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ssZZ").parse(dateTimeStamp);
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
To get the timestamp just use java.sql.Timestamp instead of java.sql.Date!
The toString() method of the java.sql.Timestamp object should return the string as you needed.
The format you are using is good but you loose Timezone offset.
If you want to consider TimeZone offset then please use below format.
java.util.Date utilDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(dateTimeStamp);
Result:
utilDate = Thu Aug 31 01:40:00 IST 2017
java.util.Date utilDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ssX").parse(dateTimeStamp);
Result:
utilDate = Thu Aug 31 07:10:00 IST 2017.
I am running this code from India and there is offset of 05:30 Hours in timezone.

How do I format a java.sql.date into this format: "MM-dd-yyyy"?

I need to get a java.sql.date in the following format "MM-dd-yyyy", but I need it to stay a java.sql.date so I can put it into a table as date field. So, it cannot be a String after the formatting, it has to end up as a java.sql.date object.
This is what I have tried so far:
java.util.Date
today=new Date();
String date = formatter.format(today);
Date todaydate = formatter.parse(date);
java.sql.Date fromdate = new java.sql.Date(todaydate.getTime());
java.sql.Date todate=new java.sql.Date(todaydate.getTime());
String tempfromdate=formatter.format(fromdate);
String temptodate=formatter.format(todate);
java.sql.Date fromdate1=(java.sql.Date) formatter.parse(tempfromdate);
java.sql.Date todate1=(java.sql.Date) formatter.parse(temptodate);
You can do it the same way as a java.util.Date (since java.sql.Date is a sub-class of java.util.Date) with a SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat(
"MM-dd-yyyy");
int year = 2014;
int month = 10;
int day = 31;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1); // <-- months start
// at 0.
cal.set(Calendar.DAY_OF_MONTH, day);
java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
System.out.println(sdf.format(date));
Output is the expected
10-31-2014
Use below code i have convert today date. learn from it and try with your code
Date today = new Date();
//If you print Date, you will get un formatted output
System.out.println("Today is : " + today);
//formatting date in Java using SimpleDateFormat
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM-dd-yyyy");
String date = DATE_FORMAT.format(today);
System.out.println("Today in MM-dd-yyyy format : " + date);
Date date1 = formatter.parse(date);
System.out.println(date1);
System.out.println(formatter.format(date1));
A simpler solution would be to just convert the date in the query to epoch before comparing.
SELECT date_column from YourTable where UNIX_TIMESTAMP(date_column) > ?;
Then, simply pass date.getTime() when binding value to ?.
NOTE: The UNIX_TIMESTAMP function is for MySQL. You'll find such functions for other databases too.
java.util.Date today=new Date();
java.sql.Date date=new java.sql.Date(today.getTime()); //your SQL date object
SimpleDateFormat simpDate = new SimpleDateFormat("MM-dd-yyyy");
System.out.println(simpDate.format(date)); //output String in MM-dd-yyyy
Note that it does not matter if your date is in format mm-dd-yyyy or any other format, when you compare date (java.sql.Date or java.util.Date) they will always be compared in form of the dates they represent. The format of date is just a way of setting or getting date in desired format.
The formatter.parse will only give you a java.util.Date not a java.sql.Date
once you have a java.util.Date you can convert it to a java.sql.Date by doing
java.sql.Date sqlDate = new java.sql.Date (normalDate.getTime ());
Also note that no dates have any built in format, it is in reality a class built on top of a number.
For anyone reading this in 2017 or later, the modern solution uses LocalDate from java.time, the modern Java date and time API, instead of java.sql.Date. The latter is long outdated.
Formatting your date
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-uuuu", Locale.US);
LocalDate fromDate = LocalDate.now(ZoneId.of("Asia/Kolkata"));
String tempFromDate = fromDate.format(formatter);
System.out.println(tempFromDate);
This prints something like
11-25-2017
Don’t confuse your date value with its textual representation
Neither a LocalDate nor a java.sql.Date object has any inherent format. So please try — and try hard if necessary — to keep the two concepts apart, the date on one side and its presentation to a user on the other.
It’s like int and all other data types. An int can have a value of 4284. You may format this into 4,284 or 4 284, 004284 or even into hex representation. This does in no way alter the int itself. In the same way, formatting your date does not affect your date object. So use the string for presenting to the user, and use LocalDate for storing into your database (a modern JDBC driver or other modern means of database access wil be happy to do that, for example through PreparedStatement.setObject()).
Use explicit time zone
Getting today’s date is a time zone sensitive operation since it is not the same date in all time zones of the world. I strongly recommend you make this fact explicit in the code. In my snippet I have used Asia/Kolkata time zone, please substitute your desired time zone. You may use ZoneId.systemDefault() for your JVM’s time zone setting, but please be aware that this setting may be changed under our feet by other parts of your program or other programs running in the same JVM, so this is fragile.

Removing time from my Date variable

I have my Date of Birth variable which is initially of type int. It is then parsed toString() and parsed to Date with simpleDateFormat.
The only issue is that it keeps returning it's default time including the date.
public Date getDob(){
String format = Integer.toString(this.dob);
try{
date = new SimpleDateFormat("ddMMyyyy").parse(format);
}catch(ParseException e){
return null;
}
return date;
}
Returns: Sat Jan 16 00:00:00 CET 1999 [ I want to remove the bold time ]
Thank you very much for your help!
Solution:
public String getDob(){
Date newDate = new Date(this.dob);
String date = new SimpleDateFormat("E MMM dd").format(newDate);
return date;
}
You cannot change toString() method of Date class,
what you are doing is you are parsing some String to Date and returning Date instance and trying to print it which internally invokes toString() of Date and it has fixed format,
You can use format() method to convert Date to String and print it in whatever format you want
A java.util.Date object by definition has both a date portion and a time-of-day portion.
Date-Time != String
Understand that a date-time object is not a String. We create String representations of the date-time value contained within a date-time object, but doing so is generating a fresh String object completely separate from the date-time object.
LocalDate
If you want only a date, without the notion of time-of-day, use the LocalDate class found in both Joda-Time and the new java.time package in Java 8 (inspired by Joda-Time).
Joda-Time
By default, Joda-Time uses the ISO 8601 standard formats. If you want Strings in other formats, explore the DateTimeFormat class (a factory of DateTimeFormatters).
Example code in Joda-Time 2.3.
String input = "01021903"; // First of February, 1903.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "ddMMyyyy" );
LocalDate dateOfBirth = formatter.parseLocalDate( input );
String outputStandard = dateOfBirth.toString(); // By default, the ISO 8601 format is used.
String outputCustom = formatter.print( dateOfBirth );
Try this one
Date originalDate = new Date();
long timeInMills = originalDate.getTime();
Date newDate = new Date(timeInMills);
String date = new SimpleDateFormat("E MMM dd").format(newDate);
System.out.println(date);
output:
Wed Apr 30
If you want to store the date in long (in milliseconds) if needed.
For more pattern have a look at SimpleDateFormat

Converting String in ISO8601 T-Z format to Date

Possible Solution:Convert Java Date into another Time as Date format
I went through it but does not get my answer.
I have a string "2013-07-17T03:58:00.000Z" and I want to convert it into date of the same form which we get while making a new Date().Date d=new Date();
The time should be in IST Zone - Asia/Kolkata
Thus the date for the string above should be
Wed Jul 17 12:05:16 IST 2013 //Whatever Time as per Indian Standard GMT+0530
String s="2013-07-17T03:58:00.000Z";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
TimeZone tx=TimeZone.getTimeZone("Asia/Kolkata");
formatter.setTimeZone(tx);
d= (Date)formatter.parse(s);
Use calendar for timezones.
TimeZone tz = TimeZone.getTimeZone("Asia/Calcutta");
Calendar cal = Calendar.getInstance(tz);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
sdf.setCalendar(cal);
cal.setTime(sdf.parse("2013-07-17T03:58:00.000Z"));
Date date = cal.getTime();
For this however I'd recommend Joda Time as it has better functions for this situation. For JodaTime you can do something like this:
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
DateTime dt = dtf.parseDateTime("2013-07-17T03:58:00.000Z");
Date date = dt.toDate();
A Date doesn't have any time zone. If you want to know what the string representation of the date is in the indian time zone, then use another SimpleDateFormat, with its timezone set to Indian Standard, and format the date with this new SimpleDateFormat.
EDIT: code sample:
String s = "2013-07-17T03:58:00.000Z";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Date d = formatter.parse(s);
System.out.println("Formatted Date in current time zone = " + formatter.format(d));
TimeZone tx=TimeZone.getTimeZone("Asia/Calcutta");
formatter.setTimeZone(tx);
System.out.println("Formatted date in IST = " + formatter.format(d));
Output (current time zone is Paris - GMT+2):
Formatted Date in current time zone = 2013-07-17T05:58:00.000+02
Formatted date in IST = 2013-07-17T09:28:00.000+05
java.time
I should like to provide the modern answer. And give you a suggestion: rather than reproducing what Date.toString() would have given you, better to use the built-in format for users in the relevant locale:
String isoString = "2013-07-17T03:58:00.000Z";
String humanReadable = Instant.parse(isoString)
.atZone(userTimeZone)
.format(localizedFormatter);
System.out.println(humanReadable);
On my computer this prints
17 July 2013 at 09.28.00 IST
My snippet uses a couple of constants
private static final ZoneId userTimeZone = ZoneId.of("Asia/Kolkata");
private static final DateTimeFormatter localizedFormatter = DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.LONG)
.withLocale(Locale.getDefault(Locale.Category.FORMAT));
The withLocale call is redundant when we just pass the default format locale. I put it in so you have a place to provide an explicit locale, should your users require a different one. It also has the nice advantage of making explicit that the result depends on locale, in case someone reading your code didn’t think of that.
I am using java.time, the modern Java date and time API. It is so much nicer to work with than the outdated Date, TimeZone and the notoriously troublesome DateFormat and SimpleDateFormat. Your string conforms to the ISO 8601 standard, a format that the modern classes parse as their default, that is, without any explicit formatter.
Same format as Date gave you
Of course you can have the same format as the old-fashioned Date would have given you if you so require. Just substitute the formatter above with this one:
private static final DateTimeFormatter asUtilDateFormatter
= DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
Now we get:
Wed Jul 17 09:28:00 IST 2013
Link to tutorial
Read more about using java.time in the Oracle tutorial and/or find other resources out there.

Categories

Resources