Convert a locale date into mysql datetime format [duplicate] - java

This question already has answers here:
Java Date - Insert into database
(10 answers)
Java: Insert into a table datetime data
(6 answers)
Closed 5 years ago.
I have the following String I get from result. How can I intelligently convert it into mysql date time format in java?
Montag, 09. April 2018, 11:00 Uhr
Thanks in advance

tl;dr
Send an object to your database, rather than a string.
myPreparedStatement.setObject( // JDBC 4.2 and later allows direct exchange of java.time objects with a database.
… ,
DateTimeFormatter.ofPattern( // Define a formatter based on a specific pattern.
"EEEE, dd. MMMM yyyy, HH:mm 'Uhr'" , // Pattern to match our input text.
Locale.GERMANY // Locale specifies human language used to parse the name of day, name of month, etc.
).parse( "Montag, 09. April 2018, 11:00 Uhr" ) // Generate a `ZonedDateTime` object.
)
Smart objects, not dumb strings
First, read the correct Answer by gil.fernandes.
Your phrase “mysql date time format” suggests working with strings. You should not be exchanging date-time values with your database as text. We have classes for that.
Parse your input string into a LocalDateTime object as shown in that answer.
DateTimeFormatter f =
DateTimeFormatter.ofPattern(
"EEEE, dd. MMMM yyyy, HH:mm 'Uhr'" ,
Locale.GERMANY
)
;
LocalDateTime ldt =
LocalDateTime.parse(
"Montag, 09. April 2018, 11:00 Uhr" ,
f
)
;
With JDBC 4.2 or later, send that object to your database. Note that LocalDateTime should only be sent to a column of type like the SQL standard TIMESTAMP WITHOUT TIME ZONE.
myPreparedStatement.setObject( … , ldt ) ;
Retrieval:
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
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
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.

You can effectively do it, but I do not know if this is a good idea.
Anyway this is what would technically work:
String s = "Montag, 09. April 2018, 11:00 Uhr";
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("EEEE, dd. MMMM yyyy, HH:mm 'Uhr'", Locale.GERMANY);
// Parse with the German format
LocalDateTime dateTime = LocalDateTime.parse(s, formatter); // Using Java 8 libraries
// Format with the MySQL format (Well, actually ISO)
final DateTimeFormatter formatterMysql = DateTimeFormatter.ISO_DATE_TIME;
System.out.println(formatterMysql.format(dateTime).replace("T", " "));
This will print out:
2018-04-09 11:00:00
Which should be understood by MySQL.

Related

Need to Format String Date in different format in java [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have a String date "30 Aug 2019". I want to format in "2019-08-30'.
I am trying with following code. It is not working.
String input = "30 Aug 2019";
Date date = sdf.parse(input);
// Date to String:
String strDate = sdf.format(date);
System.out.println(strDate);
I am getting an error as
Exception in thread "main" java.text.ParseException: Unparseable date: "30 Aug 2019"
Please help me, how to go ahead ?
tl;dr
You are using terrible date-time classes that were outmoded years ago by the adoption of JSR 310. Use java.time.LocalDate instead.
And you neglected to specify a formatting pattern to match your input string. We do so here using the DateTimeFormatter class.
LocalDate
.parse(
"30 Aug 2019" ,
DateTimeFormatter.ofPattern( "d MMM uuuu" ).withLocale( Locale.US )
)
.toString()
2019-08-30
java.time
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
Specify a Locale on your DateTimeFormatter to determine the human language and cultural norms needed for translating name of month, and such.
String input = "30 Aug 2019" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "d MMM uuuu" ).withLocale( Locale.US ) ;
LocalDate ld = LocalDate.parse( input , f ) ;
See this code run live at IdeOne.com.
ld.toString(): 2019-08-30
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.
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.
Although you should use java.time classes, to answer your question, you need 2 SimpleDateFormats; one for parsing and one for formatting:
SimpleDateFormat sdfIn = new SimpleDateFormat("dd MMM yyyy");
SimpleDateFormat sdfOut = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdfIn.parse("30 Aug 2019");
String strDate = sdfOut.format(date);
System.out.println(strDate); // 2019-08-30

Date conversion according to user timezone [duplicate]

This question already has answers here:
Calendar returns date in wrong time zone
(5 answers)
Getting the current time millis from device and converting it into a new date with different timezone [duplicate]
(2 answers)
DateFormat parse - not return date in UTC
(1 answer)
Closed 4 years ago.
We are converting database date into required user timezone. But if we format using jodatime in string format we are getting correct date and if we parse string to get date object we are getting wrong time. Here is my code. I tried jodatime parser and java date
public class Test {
public static void main(String[] args) {
String dateF = "01/19/2019 at 07:35 PM (UTC)";
String dateFormat = "MM/dd/yyyy 'at' hh:mm a (zzz)";
long time = 1603305000;
String timeZone = "Etc/UTC";
Locale locale=new Locale("en", "US");
DateTimeFormatter dateFormatter = null;
if (locale.equals(Locale.FRENCH)) {
dateFormatter = DateTimeFormat.forPattern(dateFormat).withLocale(locale);
} else {
dateFormatter = DateTimeFormat.forPattern(dateFormat).withLocale(null);
}
if (true) {
dateFormatter = dateFormatter.withZone(DateTimeZone.forID(timeZone));
}
// Old Logic using Java Time
DateFormat format3 = new SimpleDateFormat(dateFormat, locale);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
if(true)
format3.setTimeZone(TimeZone.getTimeZone(timeZone));
DateTime jodatime = new DateTime(time);
try {
System.out.println(dateFormatter.print(jodatime));
System.out.println("timezone converted Date : " + format3.parse(dateFormatter.print(jodatime)));
System.out.println("dateFormatter.parseDateTime converted Date : " + dateFormatter.parseDateTime(dateFormatter.print(jodatime)).toDate());
} catch (Exception e) {
System.out.println(e);
}
}
}
Correct date in Formatted string 01/19/1970 at 01:21 PM (UTC)
We are getting a wrong result after parsing
timezone converted Date : Mon Jan 19 18:51:00 IST 1970
dateFormatter.parseDateTime converted Date : Mon Jan 19 18:51:00 IST 1970
Correct date in Formatted Date : Mon Jan 19 01:21:00 UTC 1970
Avoid legacy date-time classes
You are using terrible old classes bundled with the earliest versions of Java. These have been supplanted entirely by the modern java.time classes.
You are also apparently mixing those legacy classes with classes from the Joda-Time library. Firstly, that mixing is ill-advised. Secondly, Joda-Time is now in maintenance-mode, with its creators advising migration to java.time. Actually, both Joda-Time and java.time projects are led by the same man, Stephen Colebourne, with the first project having been the inspiration and education for the second.
Smart objects, not dumb strings
We are converting database date
Then avoid all the string manipulations you are doing.
As of JDBC 4.2, you can directly exchange java.time objects with your database. For a moment, meaning a column of a type akin to the SQL-standard TIMESTAMP WITH TIME ZONE, use OffsetDateTime class.
myPreparedStatement.setObject( … , myOffsetDateTime ) ;
…and…
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Most databases store moments in UTC. You may want to adjust into a time zone for presentation to users. Apply a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
Generate text in a certain format by using DateTimeFormatter object. Either specify a custom formatting pattern or automatically localize by calling ofLocalized… methods.
All of this has been covered many many many times on Stack Overflow already. Search to learn more.
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.

Converting Date to 08:00:00.000+0000

I am calling a rest web service that accepts Date. On client side, i have calling this service using JDK 8 OffsetDateTime Class.
Value that is going from my client side : 2018-07-01T05:30+05:30
Value that is accepted by Service : 2018-07-01T08:00:00.000+0000
Below is the code:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(ZoneId.of("UTC")));
cal.set(2018, 05, 31);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.HOUR_OF_DAY, 0);
OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant(cal.getTime().toInstant(), ZoneId.systemDefault());
Value of offsetDateTime that is coming with above code is 2018-07-01T05:30+05:30.
I am in IST time zone.
Can someone help as to what needs to be done to change date to 2018-07-01T08:00:00.000+0000.
tl;dr
If you want 8 AM on first day of July at UTC…
OffsetDateTime.of(
2018 , 7 , 1 , // Date (year, month 1-12 is Jan-Dec, day-of-month)
8 , 0 , 0 , 0 , // Time (hour, minute, second, nano)
ZoneOffset.UTC // Offset-from-UTC (0 = UTC)
) // Returns a `OffsetDateTime` object.
.format( // Generates a `String` object with text representing the value of the `OffsetDateTime` object.
DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSZ" , Locale.US )
) // Returns a `String` object.
2018-07-01T08:00:00.000+0000
Avoid legacy date-time classes
Never use Calendar or Date classes. They were completely supplanted by the modern java.time classes such as OffsetDateTime. You are mixing the legacy classes with the modern, and that makes no sense.
java.time
Your Question is not clear about what are your inputs and what are your outputs versus your expectations.
If you goal is 8 AM on July 1 in UTC:
LocalDate ld = LocalDate.of( 2018 , Month.JULY , 1 ) ;
LocalTime lt = LocalTime.of( 8 , 0 ) ;
OffsetDateTime odt = OffsetDateTime.of( ld , lt , ZoneOffset.UTC ) ;
odt.toString(): 2018-07-01T08:00Z
That string format complies with ISO 8061 standard. If your destination refuses that input and accepts only 2018-07-01T08:00:00.000+0000, then we must defining a formatting pattern.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSZ" , Locale.US );
String output = odt.format( f );
2018-07-01T08:00:00.000+0000
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
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 think the below code will work
public static Date ConvertToGMT() {
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date utc = new Date(dateFormat.format(date));
return utc;
}
You can do it like so,
offsetDateTime.atZoneSameInstant(ZoneId.of("Asia/Kolkata"))
Update
If you need an instance of OffsetDateTime here it is.
offsetDateTime.atZoneSameInstant(ZoneId.of("Asia/Kolkata")).toOffsetDateTime();
It’s not the answer you asked for, but it may be the answer you prefer in the end: Check once more whether the service you are calling accepts the format that you are already giving it. Both formats conform with ISO 8601, so it seems that the service accepts this standard format. If so, it should accept yours too.
In any case, use OffsetDateTime and the other classes from java.time exclusively and avoid the old and outdated Calendar and TimeZone classes. Basil Bourque’s answer shows the good solution.
Link: Wikipedia article: ISO 8601

Showing wrong date (java.util.Calendar)

I'm trying to format the date as per requirement. Requirement is if two date consist different years then there should be different format and if month is different then different format.
Here is code
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.'SSSX");
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse("2018-01-16T00:07:00.000+05:30"));
Calendar cal2 = Calendar.getInstance();
cal2.setTime(sdf.parse("2018-03-18T00:07:00.000+05:30"));
SimpleDateFormat simpleDateformat = new SimpleDateFormat("E DD MMMM YYYY");
if(cal.get(Calendar.YEAR) != cal2.get(Calendar.YEAR)){
stringBuilder.append(simpleDateformat.format(cal.getTime())).append(" - ").append(simpleDateformat.format(cal2.getTime()));
System.out.println("formatis"+stringBuilder.toString());
}
if(cal.get(Calendar.MONTH) != cal2.get(Calendar.MONTH)){
SimpleDateFormat diffMonthFormat = new SimpleDateFormat("E DD MMMM");
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(diffMonthFormat.format(cal.getTime())).append(" - ").append(simpleDateformat.format(cal2.getTime()));
System.out.println("formatis"+ strBuilder.toString());
}
Problem is it's working fine for different years but when i'm comparing month then output is
Tue 16 January - Sun 77 March 2018
It's showing date as 77.
Can anyone help
Day-of-month versus Day-of-year
Formatting codes are case-sensitive.
Your use of DD uppercase in SimplDateFormat is incorrect, as it means day-of-year (1-365, or 1-366 in a Leap Year). You are getting 77 for a date in March that is the seventy-seventh day into the year, 77 of 365. Use dd lowercase instead.
Your bigger problem is using the outmoded terrible classes. Use java.time instead.
java.time
You are using troublesome obsolete classes, now supplanted by the java.time classes.
DateTimeFormatter
Define your pair of DateTimeFormatter objects for generating output. Note the use of Locale argument to specify the human language and cultural norms used in localizing. Use single d instead of dd if you do not want to force a padding zero for single-digit values.
DateTimeFormatter withoutYear = DateTimeFormatter.ofPattern( "EEE dd MMMM" , Locale.US ) ;
DateTimeFormatter withYear = DateTimeFormatter.ofPattern( "EEE dd MMMM uuuu" , Locale.US ) ;
OffsetDateTime
Parse input as a OffsetDateTime as it includes an offset-from-UTC but not a time zone.
Your input strings comply with standard ISO 8601 formatting, used by default in the java.time classes. So no need to specify formatting pattern.
OffsetDateTime odtA = OffsetDateTime.parse( "2018-01-16T00:07:00.000+05:30" ) ;
OffsetDateTime odtB = …
Year & Month
Test their year part via Year class. Ditto for Month enum.
if( Year.from( odtA ).equals( Year.from( odtB ) ) ) {
// … Use `withoutYear` formatter.
} else if( Month.from( odtA ).equals( Month.from( odtB ) ) ) { // If different year but same month.
// … Use `withYear` formatter.
} else { // Else neither year nor month is the same.
// …
}
Generate string
To generate a string, pass the formatter to the date-time’s format method.
String output = odtA.format( withoutYear ) ; // Pass `DateTimeFormatter` to be used in generating a String representing this date-time object’s value.
By the way, there is also a YearMonth class if you are ever interested in year and month together.
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
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.

Timezone differences with GMT causing hours to change?

Below is my input date string format:
2025-08-08T15%3A41%3A46
I have to convert above string date in the format as shown below:
Fri Aug 08 15:41:46 GMT-07:00 2025
And I got below code:
SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
String decodedDate = URLDecoder.decode("2025-08-08T15%3A41%3A46", "UTF-8");
Date date = dateParser.parse(decodedDate);
//Decode the given date and convert to Date object
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT-07:00"));
System.out.println(sdf.format(date));
And this is what it prints out on the console. I am not sure why it prints different hour value as compared to what I have above in the desired output. It should print out 15 but it is printing 03.
Fri Aug 08 03:41:46 GMT-07:00 2025
I am not sure what is the reason why hours are getting changed because of timezone difference with GMT?
That is the same time except in the first format you are using "HH" for hour that is "Hour in day (0-23)" and second format uses "hh" that is "Hour in am/pm (1-12)".
As the other Answer correctly states, your formatting pattern used incorrect characters.
Let's look at an alternative modern approach.
ISO 8601
Your input string, once decoded to restore the COLON characters, is in standard ISO 8601 format.
URLDecoder.decode("2025-08-08T15%3A41%3A46", "UTF-8")
2025-08-08T15:41:46
Using java.time
You are using troublesome old date-time classes, now legacy, supplanted by the java.time classes.
The java.time classes use ISO 8601 by default when parsing/generating strings.
Your input string lacks any indication of offset-from-UTC or time zone. So we parse as a LocalDateTime.
LocalDateTime ldt = LocalDateTime.parse( "2025-08-08T15:41:46" )
ldt.toString(): 2025-08-08T15:41:46
If you know the intended time zone, assign a ZoneId to produce a ZonedDateTime.
ZonedDateTime zdt = ldt.atZone( ZoneId.of( "America/Montreal" ) ) ;
zdt.toString(): 2025-08-08T15:41:46-04:00[America/Montreal]
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.

Categories

Resources