I am getting date in following format, as java string:
Sat Jan 01 00:00:00 CET 2000
i want to convert it to yyyy-MM-dd fromat. For this i am doing:
String strDate = "Sat Jan 01 00:00:00 CET 2001";
SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd");
try{
Date parsed = sdf.pa开发者_运维百科rse(strDate);
}catch(Exception e){
System.out.println("Exception: " + e.getMessage());
}
But i am getting exception: Unparseable date: "Sat Jan 01 00:00:00 CET 2001"
Please give me some solution for this.
Thank you
The SimpleDateFormat needs to be the input date format, then you can use another SimpleDateFormat to get the appropriate output format, i.e.:
String strDate = "Sat Jan 01 00:00:00 CET 2001";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
SimpleDateFormat outputDate = new SimpleDateFormat("yyyy-MM-dd");
try{
Date parsed = sdf.parse(strDate);
}
catch(Exception e){
System.out.println("Exception: " + e.getMessage());
}
System.out.println("Date: " + outputDate.format(parsed));
You need a SimpleDateFormat to parse the existing string and another SimpleDateFormat to format the parsed Date object into the appropriate yyyy-MM-dd string.
You can use applyPattern to change the current pattern in the SimpleDateFormat so you don't have to create a new object.
I'll leave the patterns as an exercise for the student.
You are trying to parse the date with the format "yyyy-MM-dd".
You need to build a SimpleDateFormat matching the format you need to parse, then use the one in your snippet to format it.
The parse format you need will be something along the lines of "EEE MMM dd HH:mm:ss z yyyy".
If your locale is not US or another english language locale, you will get an exception, because Sat is not known, so you should specify the locale in your input format.
Try this:
String dateAsString = "Sat Jan 01 00:00:00 CET 2001";
SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Date: " + outputFormat.format(inputFormat.parse(dateAsString)));
ps: Jan 01 2001 is not a Saturday :)
Your pattern needs to match the date you are parsing, something like this: Look at the SimpleDateFormat doc for complete instructions.
SimpleDateFormat sdf = new SimpleDateFormat ("EEE MMM dd hh:mm:ss zzz yyyy");
tl;dr
After fixing your faulty input text, this value can be parsed using the modern java.time classes.
ZonedDateTime.parse(
"Mon Jan 01 00:00:00 CET 2001" // Changed incorrect "Sat" to correct "Mon".
,
DateTimeFormatter.ofPattern(
"EEE MMM dd HH:mm:ss z uuuu"
,
Locale.US // Specify a `Locale` to determine human language and cultural norms used in translation.
) // Returns a `DateTimeFormatter` object to be passed as second argument to `parse` method.
) // Returns a `ZonedDateTime` object.
.toString() // Generates a `String` using standard ISO 8601 format extended by appending zone name in square brackets.
2001-01-01T00:00+01:00[Europe/Paris]
Wrong input
Your example input string "Sat Jan 01 00:00:00 CET 2001"
is incorrect. January 1, 2001 was a Monday, not a Saturday. See calendar display.
Furthermore, early in your Question you use the year 2000, while later you use 2001.
Details
The Answer by Lazarus is correct, but uses now-outmoded classes. It is correct in that your formatting pattern failed to match the input string.
First we must fix your faulty input string, changing "Sat" to be "Mon".
String input = "Mon Jan 01 00:00:00 CET 2001"; // After altering the original input string, fixing "Sat" to be "Mon".
Use only java.time classes for your date-time work. These replace Date
& Calendar
etc.
Define a formatting pattern to match your input string. Specify a Locale
to determine the human language and cultural norms used in translating from the input string.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
Generate a String
in standard ISO 8601 format extended by appending the name of the time zone in square brackets.
String output = zdt.toString() ;
System.out.println(output);
2001-01-01T00:00+01:00[Europe/Paris]
To see the same moment in UTC, extract a Instant
.
Instant instant = zdt.toInstant() ;
instant.toString(): 2000-12-31T23:00:00Z
Tips
- Your input string uses a terrible format. Always use standard ISO 8601 formats for exchanging date-time values as text.
- Specify a proper time zone name in the format of
continent/region
, such asAmerica/Montreal
,Africa/Casablanca
, orPacific/Auckland
. Never use the 3-4 letter abbreviation such asCET
,EST
, orIST
as they are not true time zones, not standardized, and not even unique(!).
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, 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.
What Date
class are you using? If you're using an IDE, it's easy to accidentally use java.sql.Date
instead of java.util.Date
by accident. Here's my complete sample program and its output:
package pkg;
import java.lang.String;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Foo
{
public static void main(String[] args) throws Exception
{
Date parsed = null;
String strDate = "Sat Jan 01 00:00:00 CET 2001";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
SimpleDateFormat outputDate = new SimpleDateFormat("yyyy-MM-dd");
try{
parsed = sdf.parse(strDate);
}
catch(Exception e){
System.out.println("Exception: " + e.getMessage());
}
System.out.println("Date: " + outputDate.format(parsed));
}
}
produced
Date: 2000-12-31
which is correct, as I'm in EST, unless I'm mistaken about where CET is. No exceptions encountered, of the parsing kind or otherwise.
I have a issue where I need to convert a date in the format of String to another string but with different format.
E.g. - "2022-05-16" convert it into "05/16/2022" i.e. "yyyy-MM-dd" to "MM/dd/yyyy".
Whenever you convert a date string from one form to another, you cannot do it directly.
First convert the string into given format and create a date object.
And then from the date object you can convert it to the format you are looking for.
Here is the code example:
public static String convertDate(String providedDate, String providedDateFormat, String finalConversionDateFormat){
StringBuffer tempStr = new StringBuffer();
//Create the SimpleDateFormat object for specific formats
SimpleDateFormat existingDateFormat = new SimpleDateFormat(providedDateFormat);
SimpleDateFormat sdf = new SimpleDateFormat(finalConversionDateFormat);
try {
//Convert the provided date into Date object with the given format.
Date tempDate = existingDateFormat.parse(providedDate);
//Once the existing date object created, convert into format whatever you are looking for
tempStr.append(sdf.format(tempDate));
} catch (java.text.ParseException e) {
//logger.error(e);
}
return tempStr.toString();
}
convertDate("2022-05-16", "yyyy-MM-dd", "MM/dd/yyyy");
精彩评论