String to Date conversion - Java - java

I am having this problem with the conversion of string to date, I want to insert into the database date of format "dd.MM.yy" using this code:
SimpleDateFormat f = new SimpleDateFormat("dd.MM.yy");
String d = f.format(new Date());
System.out.println("String: " + d);
Date d1 = f.parse(d);
System.out.println("Date: " +d1);
Output:
String: 16.06.17
Date: Fri Jun 16 00:00:00 EEST 2017
I tried other methods but the date is always printing in this format "EE MMM dd HH:mm:ss z yyyy".

Your code is working fine. Date class overrides the .toString() method so when you do System.out.println("Date: " +d1) you're actually doing System.out.println("Date: " + d1.toString());
If you want to print your date with the format you provide you'll need to use format() from your SimpleDateFormat:
SimpleDateFormat f = new SimpleDateFormat("dd.MM.yy");
String d = f.format(new Date());
System.out.println("String: " + d);
Date d1 = f.parse(d);
System.out.println("Date: " + f.format(d1));

dd.MM.YY is not a valid sql type date. So you can not use this format directly to your database. If it is required you can use an alternative by making database field as varchar so it can accept your formatted date.And when you want to use this date you can simply format back this.
// For example retrieved from database.
String date = "2012/12/12";
SimpleDateFormat f = new SimpleDateFormat("dd.MM.yy");
Date newDate = f.format(new Date(date)); // Will hold date 12.12.12

Excuse me, but you are doing a number of things wrong.
While displaying two-digit years to the user is OK in situations where the century in unambiguous, you should never store two-digit years to your database. You are creating another Y2K problem. If you want to store years as string, store four digits.
But don’t store strings. Your RDBMS no doubt has a date datatype exactly made for and suited for storing dates. Use it instead.
In Java don’t use the long outdated classes SimpleDateFormat and Date. Their replacements came out in 2014. So use LocalDate for dates. Get a new JDBC driver (it should be JDBC 4.2 compliant) and store your LocalDate directly into the date typed column of your database. No need for any formatting.
In case you need to display your date to the user in dd.MM.yy format, use DateTimeFormatter:
LocalDate myDate = LocalDate.of(2017, Month.JUNE, 16);
System.out.println("The date is "
+ myDate.format(DateTimeFormat.ofPattern("dd.MM.yy")));
(I have not tested; if there’s a typo you cannot fix yourself, please revert.)
PS
the date is always printing in this format "EE MMM dd HH:mm:ss z yyyy".
Yes, java.util.Date prints that way. Always. A Date object does not hold a format in it (the same holds true for LocalDate). This has been explained in many places. See for example All about java.util.Date, scroll down to the section How do I convert a Date to a different format?

Related

How to convert two different string dates into a single date format

I have two strings that I want to convert into a particular date time format so I can do a comparison. Problem I have is that it errors out in the parse with an exception and I wonder if I am doing something wrong. Wanted to ask what is the best way to convert two different string dates into a single date format
SimpleDateFormat localDateFormat = new SimpleDateFormat("yyyy dd mm - HH:mm:ss");
String firstDateString= "11 May 2018 21:03:51 GMT";
String secondDateString= "dataStore.get("2018-05-11T21:03:51Z";
Date firstDateFormat =localDateFormat.parse(firstDateString);
Date secondDateFormat =localDateFormat.parse(secondDateString);
Problem I have is that it errors out in the parse with an exception
and I wonder if I am doing something wrong.
=> Yes you are doing it actually. You first need to parse the date into it's actual format and then format it into the desired format.
For example: for parsing and formatting 2018-05-11T21:03:51Z
DateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:MM:SS'z'", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat("yyyy dd mm - HH:mm:ss");
Date date = originalFormat.parse("2018-05-11T21:03:51Z");
String formattedDate = targetFormat.format(date); // 2018 05 11 - 21:03:51
Here:
SimpleDateFormat localDateFormat = new SimpleDateFormat("yyyy dd mm - HH:mm:ss");
That format says: 4 year digits SPACE 2 day digits SPACE 2 month digits DASH and so on.
Thing is: neither your string dates:
"11 May 2018 21:03:51 GMT"
"2018-05-11T21:03:51Z"
Look like that. The first one is rather "dd M yyy ..." (doesnt start with year), and the second one uses "-" not " " as separator for the initial date.
Answer: you have to use a pattern that really matches the expected date strings, see here for the specs. And note for example that you will need to use M to match "May", the lowercase m is about digits, not words!
And note: the second example is an ISO date, and the DateTimeFormatter already has pre-defined formatters for those! (so be careful about re-inventing the wheel)
java.time
DateTimeFormatter firstFormatteer
= DateTimeFormatter.ofPattern("d MMM uuuu H:mm:ss z", Locale.ENGLISH);
String firstDateString = "11 May 2018 21:03:51 GMT";
String secondDateString = "2018-05-11T21:03:51Z";
Instant firstInstant = firstFormatteer.parse(firstDateString, Instant::from);
Instant seoncdInstant = Instant.parse(secondDateString);
System.out.println("The strings are parsed into " + firstInstant + " and " + seoncdInstant);
Output is:
The strings are parsed into 2018-05-11T21:03:51Z and 2018-05-11T21:03:51Z
Your strings from two services are in two different formats, and the best you can do is to handle them in two different ways. For the first, define a formatter that matches the format. The second is in ISO 8601 format. Instant parses this format without any explicit formatter, so here we don’t need to define one.
To compare do for example:
if (firstInstant.isBefore(seoncdInstant)) {
System.out.println("The first date and time comes first");
} else if (firstInstant.equals(seoncdInstant)) {
System.out.println("The date and time is the same");
}
The date and time is the same
The Instant class is the modern replacement for the Date class, it represents a moment in time.
The Date class was poorly designed and SimpleDateFormat notoriously troublesome, fortunately they are both long outdated. I recommend you avoid them and use java.time, the modern Java date and time API, instead.
Link: Oracle tutorial: Date Time explaining how to use java.time.

Issue with ISO 8601 in Android API level 23

I've issue in format of java for ISO 8601, I'm using this code
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
//yyyy-MM-dd'T'HH:mm:ss.shh:mm
Date date = Calendar.getInstance().getTime();
String cDate = format.format(date);
Log.d("Date","Date is " + cDate);
My result is:
Date is 2019-04-03T04:37:52+0000
if I'm using this format yyyy-MM-dd'T'HH:mm:ssZ. And the result is:
Date is 2019-04-03T04:49:33.3304:49
if I'm using this format yyyy-MM-dd'T'HH:mm:ss.shh:mm. I've been tried my solutions but not is giving me my desired solution.
My desired solution is 2008-09-15T15:53:00+05:00. I try Offset but it's not working for API level 23, It's only for API level 28.
Here is the format mask you should be using:
yyyy-MM-dd'T'HH:mm:ssXXX
From the documentation for SimpleDateFormat, we can see that X represents the ISO 8601 time zone, which shows the timezone in terms of hours shifted from GMT.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
format.setTimeZone(TimeZone.getTimeZone("Africa/Cairo"));
Date date = Calendar.getInstance().getTime();
String cDate = format.format(date);
System.out.println("Date is " + cDate);
Date is 2019-04-03T06:41:30+02:00
Note that I needed to assign a time zone other than GMT, because GMT just returns Z for the time zone.
Tim was right but his given pattern works for java, Not for that java which is in android.
For Android java use this pattern
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ");
Then out put will be
Date is 2019-04-03T08:29:27+00:00

How to set format of current date time to different format?

I use the following code to retrieve the current date and time, then add it to table using following method.
Change 2013-07-29 23:20:34.0 to 29th July 2013, 11:20 PM
DateTime
public Date getCurrentDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
System.out.println("current:" + dateFormat.format(date));
return date;
}
Hibernate
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
public Date getCurrentDateTime() {
return date;
}
A Date object doesn't have a format. (Neither java.sql.Date nor java.util.Date.) The database will just store it in the table in whatever native representation it chooses (almost certainly not text) and when you retrieve the data it's up to you to format it how you wish.
To change the format used by System.out.println, just change the pattern you're passing to the SimpleDateFormat constructor - see the documentation for details. Note that you should consider which time zone and Locale you're interested in, too - for example, month names won't be the same between different locales, and different locales also have different expected formats. (Even within the same language, there are different conventions.)
You'll find the "th" of "29th" hard to handle with SimpleDateFormat - I don't believe it supports ordinals. This question may help you though. (It's going to be ugly code, mind you - I would suggest changing the format to remove the ordinal if you possibly can.)
To change the day to ordinal number you need to use the following suffix. have a look at this link as well
DD + TH = DDTH result >>>> 4TH
OR to spell the number add SP to the format
DD + SPTH = DDSPTH result >>> FOURTH
Also use the fmt library to format the date on jsp pages
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:formatDate type="both" dateStyle="long" timeStyle="short"
value="${date}"/>
Something similar to this ??
for hibernate
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String dateBufferString = format.format(date);
Date dateBuffer;
try {
dateBuffer = format.parse(dateBufferString);
System.out.println("Database Date Format :" + date);
System.out.println("(dd-MM-yyyy) date: " + format.format(date));
System.out.println("dateBufferSTring " + dateBufferString);
System.out.println("dateBuffer: " + dateBuffer);

Java parsing String to a Date returns incorrect Date

I am storing my 2 Java date types as Date and Time for a MySQL database table. I am using the SimepleDateFormat("YYYY-MM-dd") to store the date in my database and it shows up as the correct date when i go to select it. However when i try to parse it back into a util.Date and create a new Event Object, it shows up as 30/12/2012 instead of 31/05/2013 as it is in the database. The time, when parsed into a util.Date and formatted prints out correctly. I am not sure why the Date is printing the wrong date, but the time is printing the correct time.
Database
+--------+--------------+-----------+
+ EVENT1 + 2013-05-31 + 02:30:00 +
+--------+--------------+-----------+
+ EVENT2 + 2013-05-31 + 01:00:00 +
+--------+--------------+-----------+
Prints:
Event1
30/12/2012
02:30
Event2
30/12/2012
01:00
It should be yyyy-MM-dd with lower case Ys. See here for what the capital Y means...
Y returns 2012 while y returns 2011 in SimpleDateFormat
Your pattern is wrong. (mm != MM, yyyy != YYYY ...)
Take a look at http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
try
String testDate = "2007-11-02T14:46:03";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = formatter.parse(testDate);
But better way to store in database is to use timestamp instead of storing date and time separately
The proper method is rs.getDate(int). Take a look at
http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html#getDate(int)
With that method you get a java.sql.Date and if you want to transform it to a java.util.Date take a look at this Converting java.sql.Date to java.util.Date
You can even do this
Date date = rs.getTimestamp(2);
By the way, is better to have your date object independent on the format you want to use to show it.
try this...
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd");
Date date = dateFormat.parse(rs.getDate(2).toString());

Why Java SimpleDateFormat().parse() is printing weird formate?

My input is String formated as the following:
3/4/2010 10:40:01 AM
3/4/2010 10:38:31 AM
My code is:
DateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss aa");
try
{
Date today = dateFormat.parse(time);
System.out.println("Date Time : " + today);
}
catch (ParseException e)
{
e.printStackTrace();
}
the output is:
Sun Jan 03 10:38:31 AST 2010
Sun Jan 03 10:40:01 AST 2010
I'm not sure from where the day (Sun) came from? or (AST)? and why the date is wrong? I just wanted to keep the same format of the original String date and make it into a Date object.
I'm using Netbeans 6.8 Mac version.
Should be MM, not mm. The lowercase mm is for minutes, not months.
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa");
MM, not mm for months. You are using mm twice - and logically, it's the same things - minutes.
If you want to print the date in the original format, use the format method:
System.out.println("Date Time : "+ dateFormat.format(today));
the "weird" format comes from Date's toString implementation, the javadoc says:
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
"I just wanted to keep the same format of the original String date and make it into a Date object."
The Date Object is intended to represent a specific instant in time, you can't keep the format of the original string into it, that's why we have the DateFormat Class.
The answer is simple. You have displayed the Date.toString() value of today and not the intended dateFormat version. what you require is:
System.out.println("Date Time : " + dateFormat.format(today) );
Printing the Date out using System.out.println() results in the toString() method being called on the Date object.
The format string used in toString() is what is causing the Day of the week and the timezone to appear in the output.
This is apart from the parsing mistake pointed out by Duffy.

Categories