Convert String datetime to Date not working Java Android [duplicate] - java

This question already has answers here:
How to parse month full form string using DateFormat in Java?
(4 answers)
Getting error java.text.ParseException: Unparseable date: (at offset 0) even if the Simple date format and string value are identical
(4 answers)
How to convert Java String "EEE MMM dd HH:mm:ss zzz yyyy"date type to Java util.Date "yyyy-MM-dd" [duplicate]
(1 answer)
Closed 1 year ago.
I don't know why I can't convert a String to a Date in Java Android. I got error when I try
The error :
W/System.err: java.text.ParseException: Unparseable date: "Fri Apr 30 00:12:13 GMT+02:00 2021"
My code :
String datestr = cursor.getString(cursor.getColumnIndex(UPDATED_AT)); // Fri Apr 30 00:12:13 GMT+02:00 2021
DateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.GERMANY);
myDate = dateFormat.parse(datestr);
Edit:
I'm up to date now (I think):
I convert all my Date to
OffsetDateTime currentDate = OffsetDateTime.now()
That gives me :
2021-04-30T02:14:49.067+02:00
Then If this date is a String and I want to convert it to OffsetDateTime :
String datestr = cursor.getString(cursor.getColumnIndex(UPDATED_AT)); // 2021-04-30T02:14:49.067+02:00
DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").withLocale( Locale.US );
OffsetDateTime myDate = OffsetDateTime.parse( datestr , f );

tl;dr
OffsetDateTime
.parse(
"Fri Apr 30 00:12:13 GMT+02:00 2021" ,
DateTimeFormatter
.ofPattern( "EEE MMM dd HH:mm:ss OOOO uuuu" )
.withLocale( Locale.US )
)
.toString()
2021-04-30T00:12:13+02:00
Avoid legacy date-time classes
You are using terrible date-time classes that were supplanted years ago by the modern java.time classes defined in JSR 310.
DateTimeFormatter
Define a formatting pattern to match your input text. Use DateTimeFormatter class.
Note the Locale, to determine the human language and cultural norms to use in translating the name of day & month, capitalization, abbreviation, and so on.
String input = "Fri Apr 30 00:12:13 GMT+02:00 2021";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss OOOO uuuu" ).withLocale( Locale.US );
OffsetDateTime
Your input represents a moment, a point on the timeline, as seen in the wall-clock time of an offset-from-UTC but not a time zone. Therefore, parse as a OffsetDateTime object.
OffsetDateTime odt = OffsetDateTime.parse( input , f );
odt.toString() = 2021-04-30T00:12:13+02:00
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….

Related

How to convert Java String "EEE MMM dd HH:mm:ss zzz yyyy"date type to Java util.Date "yyyy-MM-dd" [duplicate]

This question already has answers here:
want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format
(11 answers)
display Java.util.Date in a specific format
(11 answers)
DateTimeParse Exception
(2 answers)
Closed 2 years ago.
My source date type is EEE MMM dd HH:mm:ss zzz yyyy. For example, Sat Dec 12 00:00:00 KST 2020 But my target date type is Java Date type with format yyyy-MM-dd. So I make the method which convert Java String type EEE MMM dd HH:mm:ss zzz yyyy to java util object.
private static Date getDate(String beforeDate) throws Exception{
SimpleDateFormat readFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
Date rdate = readFormat.parse(beforeDate);
SimpleDateFormat writeFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
String format = writeFormat.format(rdate);
System.out.println(format);
return writeFormat.parse(format);
}
System.out.println(format) line prints the right values which I expect.
2020-12-12
2020-12-12
2013-01-01
But the type of return values is wrong. The return value from the method seems not to be influenced.
System.out.println(getDate("Sat Dec 12 00:00:00 KST 2020"));
The above line prints Sat Dec 12 00:00:00 KST 2020 again. I have no idea which codes are wrong in converting Java date type.
tl;dr
ZonedDateTime
.parse(
"Sat Dec 12 00:00:00 KST 2020" ,
DateTimeFormatter
.ofPattern( "EEE MMM dd HH:mm:ss zzz uuuu" )
.withLocale( Locale.US )
)
.toLocalDate()
.toString()
2020-12-12
Avoid legacy date-time classes
You are using terrible date-time classes that were supplanted years ago by the modern java.time classes. Never use Date, Calendar, or SimpleDateFormat.
You said:
my target date type is Java Date type with format yyyy-MM-dd.
Apparently, you expect Date to hold a date. It does not. The java.util.Date class represents a moment, a date with time-of-day as seen in UTC. The java.sql.Date class pretends to hold only a date, but it too actually contains a date with time-of-day as seen in UTC.
Among the many problems with java.util.Date class is the behavior of its toString method. That method dynamically applies the JVM’s current default time zone while generating text. This anti-feature may contribute to your confusion.
LocalDate
Instead you should be using java.time.LocalDate to represent a date-only value without a time-of-day and without a time zone or offset-from-UTC.
ZonedDateTime
First use the DateTimeFormatter class to parse your entire input string. This results in a ZonedDateTime object representing a moment as seen through the wall-clock time used by the people of a particular region.
Example code
String input = "Sat Dec 12 00:00:00 KST 2020" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss zzz uuuu" ).withLocale( Locale.US ) ;
ZonedDateTime zdt = ZonedDateTime.parse( input , f ) ;
From that ZonedDateTime object, extract a LocalDate.
LocalDate localDate = zdt.toLocalDate() ;
See this code run live at IdeOne.com.
zdt.toString(): 2020-12-12T00:00+09:00[Asia/Seoul]
ld.toString(): 2020-12-12
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….

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

Convert a locale date into mysql datetime format [duplicate]

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.

Java date format - GMT +04:00 [duplicate]

This question already has answers here:
java parsing string to date
(2 answers)
how to parse output of new Date().toString()
(4 answers)
Closed 2 years ago.
I have to parse the following date
Fri Sep 30 18:31:00 GMT+04:00 2016
and it is not working with the following pattern:
new SimpleDateFormat("EEE MMM dd HH:mm:ss z YYYY", Locale.ENGLISH);
I get the following date as output: Fri Jan 01 18:31:00 GMT+04:00 2016.
Could you please tell me what I am doing wrong?
It should be lower case "y":
EEE MMM dd HH:mm:ss z yyyy
Upper case "Y" means weekBasedYear:
a date can be created from a week-based-year, week-of-year and
day-of-week
I guess mixing the week-based and absolute/era patterns just does not work well for parsing.
tl;dr
OffsetDateTime
.parse
(
"Fri Sep 30 18:31:00 GMT+04:00 2016" ,
DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss O uuuu" , Locale.US )
)
.toString()
2016-09-30T18:31+04:00
Avoid legacy classes
The other Answers are now outmoded. The terrible Date, Calendar, and SimpleDateFormat classes are now legacy, supplanted years ago by the modern java.time classes defined in JSR 310.
java.time
Your input string represents a date with time-of-day in the context of an offset-from-UTC. An offset is a number of hours ahead or behind of the baseline of UTC. For this kind of information, use OffsetDateTime class.
Note that an offset-from-UTC is not a time zone. A time zone is a history of the past, present, and future changes to the offset used by the people of a particular region.
The DateTimeFormatter class replaces SimpleDateFormat. The formatting codes are similar, but not exactly the same. So carefully study the Javadoc.
Notice that we pass a Locale. This specifies the human language and cultural norms to use in parsing the input, such as the name of the month, name of the day-of-week, the punctuation, the capitalization, and so on.
package work.basil.example.datetime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Parsing
{
public static void main ( String[] args )
{
Parsing app = new Parsing();
app.demo();
}
private void demo ( )
{
String input = "Fri Sep 30 18:31:00 GMT+04:00 2016";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss O uuuu" , Locale.US );
OffsetDateTime odt = OffsetDateTime.parse( input , f );
System.out.println( "odt = " + odt );
}
}
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
Below code is working fine
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class ParseDate {
public static void main(String[] args) {
try {
SimpleDateFormat parserSDF = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
Date date = parserSDF.parse("Fri Sep 30 18:31:00 GMT+04:00 2016");
System.out.println("date: " + date.toString());
} catch (ParseException ex) {
ex.printStackTrace();
}
}
}

Parsing a String to Date [duplicate]

This question already has answers here:
Java Date Error
(8 answers)
Closed 4 years ago.
String that I want to parse:
Sun Nov 10 10:00:00 CET 2013
My code:
substrings = "Sun Nov 10 10:00:00 CET 2013"
SimpleDateFormat parserSDF = new SimpleDateFormat("EEE MMM d HH:mm:ss ZZZ yyyy");
Date date = parserSDF.parse(substrings);
Compiler error output:
java.text.ParseException: Unparseable date: "Sun Nov 10 10:00:00 CET 2013"
at java.text.DateFormat.parse(Unknown Source)
...
Probably you are missing the correct Locale. Try this, in your example:
SimpleDateFormat parserSDF = new SimpleDateFormat("EEE MMM d HH:mm:ss ZZZ yyyy", Locale.US);
ZZZ will attempt to format the time zone in accordance to RFC 822 time zone, use zzz instead.
Here's the JavaDoc link for reference
java.time
The modern approach uses the java.time classes.
String input = "Sun Nov 10 10:00:00 CET 2013";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss z uuuu" , Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
zdt.toString(): 2013-11-10T10:00+01:00[Europe/Paris]
The terrible old java.util.Date class was replaced years ago by the java.time.Instant class. Both represent a moment in UTC. To adjust from the time zone seen above to UTC, simply extract a Instant object.
Instant instant = zdt.toInstant() ; // Adjust from time zone to UTC.
Avoid java.util.Date. But if you must interoperate with old code not yet updated to java.time, you can convert back and forth. See the new methods added to the old classes, such as Date.from and Date::toInstant methods.
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.
The problem is that parserSDF takes a string rather than an array and a ParsePosition. I wrote this to output what I think you want.
import java.text.*;
public class Parser{
public static void main(String[] args){
String input = "Sun Nov 10 10:00:00 CET 2013";
SimpleDateFormat parserSDF = new SimpleDateFormat("EEE MMM d HH:mm:ss ZZZ yyyy");
System.out.println(parserSDF.parse(input, new ParsePosition(0)));
}
}
I recommend taking a look at SimpleDateFormat and ParsePosition within the API

Categories

Resources