Parsing a java Date back from toString() [duplicate] - java

This question already has answers here:
how to parse output of new Date().toString()
(4 answers)
Closed 3 years ago.
I have a String containing the result of toString() called on an instance of java.util.Date. How can I parse this value back to a Date object?
The Java docs say that toString() converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
but of course there is no such format tag as "dow" or "mon".
Could someone please help me with this problem. Please note that unfortunately the toString() call is in a piece of code out of my control.

If you don't have control over the code that's generating the String:
To parse the toString() format you need to set the SimpleDateFormat locale to english and use the format: "EEE MMM dd HH:mm:ss Z yyyy".
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", new Locale("us"));`

I didn't test but something like this probably would work:
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM HH:mm:ss z yyyy");
Date date = sdf.parse(dateStr);
If not, try to correct it using documentation:
http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#toString()
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

First take a look at all the date formats provided by java Date Formats.
And you can use SimpleDateFormat class to do what you want.
public class DateFormatTest
{
public DateFormatTest()
{
String dateString = // in "dow mon dd hh:mm:ss zzz yyyy" format
SimpleDateFormat dateFormat = new SimpleDateFormat("dow mon dd hh:mm:ss zzz yyyy");
Date convertedDate = dateFormat.parse(dateString);
System.out.println("Converted string to date : " + convertedDate);
}
public static void main(String[] argv)
{
new DateFormatTest();
}
}
}

Use simpledateformat. Find the doumentation here:
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Suppsoe you get String of "dateString" ;
SimpleDateFormat sdf = new SimpleDateFormat("dow mon dd hh:mm:ss zzz yyyy");
Date date = sdf.parse("dateString");

Related

Parse Date, CET vs CEST, invalid TimeZone, unparseable

I am using shannah´s Data Access Library to access my objects via his DAO interfaces.
I face a very strange behaviour with parsing the date values when the unmap method gets called once my stuff is in the database. It only fails on CEST (Central European Summer Time)
I tried to use the NumberUtil.dateValue Method to parse it but it still fails...
java.lang.RuntimeException: Failed to parse string date format Thu Mar 31 00:00:00 CEST 2016. Could not find appropriate format parser.
i defined DateFormat´s as these
dateFormats[0] = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
dateFormats[1] = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy");
dateFormats[2] = new SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZZ yyyy");
dateFormats[3] = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy");
also tried to trim the String but it didnt help.
Im out of ideas as SDF doesnt have the constructor as the normal JDK with the 2nd parameter beeing the Locale.
// Method that take date time string , input pattern and out put pattern,that return formatted date as string
public String parseDate(String dateTime,String inputPattern, String outputPattern) throws ParseException {
SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern, Locale.ENGLISH);
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
Date date = inputFormat.parse(dateTime);
String str = outputFormat.format(date);
return str;
}
// call method
String date = parseDate("Thu Mar 31 00:00:00 CEST 2016" ,"EEE MMM dd HH:mm:ss zzz yyyy", "MM-dd-yyyy:HH:mm:ss");
// print date
System.out.println(date);
// Result
03-31-2016:03:00:00
I now did a workaround to this issue, i can still develop my api and stuff further but to be honest i dont like this fix, as i think it will make some problems with the TimeZones later.
Can someone with more experience tell me anything about this fix, if it may cause errors with TimesZones and Summer/Winter times?
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy");
String dateValue = plannedDate;
String year = dateValue.substring(dateValue.length() - 4);
dateValue = dateValue.substring(0, 20);
dateValue += year;
this.plannedDate = sdf.parse(dateValue);
Any advice or possible fixes are welcome (y)

How to convert Date to a particular format in android?

"Mar 10, 2016 6:30:00 PM" This is my date and I want to convert this into "10 Mar 2016". Can I use SimpleDateFormat in android. I am not getting the exact pattern to convert it. Please help and thanks in advance
String date="Mar 10, 2016 6:30:00 PM";
SimpleDateFormat spf=new SimpleDateFormat("Some Pattern for above date");
Date newDate=spf.format(date);
spf= new SimpleDateFormat("dd MMM yyyy");
String date = spf.format(newDate);
Will this steps work? If yes, can someone please give me a pattern of that format? Thanks in advance.
This is modified code that you should use:
String date="Mar 10, 2016 6:30:00 PM";
SimpleDateFormat spf=new SimpleDateFormat("MMM dd, yyyy hh:mm:ss aaa");
Date newDate=spf.parse(date);
spf= new SimpleDateFormat("dd MMM yyyy");
date = spf.format(newDate);
System.out.println(date);
Use hh for hours in order to get correct time.
Java 8 and later
Java 8 introduced new classes for time manipulation, so use following code in such cases:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd, yyyy h:mm:ss a");
LocalDateTime dateTime = LocalDateTime.parse(date, formatter);
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("dd MMM yyyy");
System.out.println(dateTime.format(formatter2));
Use h for hour format, since in this case hour has only one digit.
conversion from string to date and date to string
String deliveryDate="2018-09-04";
SimpleDateFormat dateFormatprev = new SimpleDateFormat("yyyy-MM-dd");
Date d = dateFormatprev.parse(deliveryDate);
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE dd MMM yyyy");
String changedDate = dateFormat.format(d);
You can use following method for this problem. We simply need to pass Current date format, required date format and Date String.
private String changeDateFormat(String currentFormat,String requiredFormat,String dateString){
String result="";
if (Strings.isNullOrEmpty(dateString)){
return result;
}
SimpleDateFormat formatterOld = new SimpleDateFormat(currentFormat, Locale.getDefault());
SimpleDateFormat formatterNew = new SimpleDateFormat(requiredFormat, Locale.getDefault());
Date date=null;
try {
date = formatterOld.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
if (date != null) {
result = formatterNew.format(date);
}
return result;
}
This method will return Date String in format you require.
In your case method call will be:
String date = changeDateFormat("MMM dd, yyyy hh:mm:ss a","dd MMM yyyy","Mar 10, 2016 6:30:00 PM");
You should parse() the String into Date and then format it into the desired format. You can use MMM dd, yyyy HH:mm:ss a format to parse the given String.
Here is the code snippet:
public static void main (String[] args) throws Exception
{
String date = "Mar 10, 2016 6:30:00 PM";
SimpleDateFormat spf = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
Date newDate = spf.parse(date);
spf = new SimpleDateFormat("dd MMM yyyy");
String newDateString = spf.format(newDate);
System.out.println(newDateString);
}
Output:
10 Mar 2016
For the sake of completeness, here is the modern version. This is for anyone reading this who either uses Java 8 or later or is happy with a (good and futureproof) external library.
String date = "Mar 10, 2016 6:30:00 PM";
DateTimeFormatter parseFormatter
= DateTimeFormatter.ofPattern("MMM d, uuuu h:mm:ss a", Locale.ENGLISH);
DateTimeFormatter newFormatter
= DateTimeFormatter.ofPattern("d MMM uuuu", Locale.ENGLISH);
date = LocalDateTime.parse(date, parseFormatter).format(newFormatter);
System.out.println(date);
This prints the desired
10 Mar 2016
Please note the use of explicit locale for both DateTimeFormatter objects. “Mar” and “PM” both are in English, so neither the parsing nor the formatting will work unless some English-speaking locale is used. By giving it explicitly we are making the code robust enough to behave as expected also on computers and JVMs with other default locales.
To use the above on Android, use ThreeTenABP, please see How to use ThreeTenABP in Android Project. On other Java 6 and 7 use ThreeTen Backport.
You need to use SimpleDateFormat class to do the needful for you
String date = "Your input date"
DateFormat originalFormat = new SimpleDateFormat("<Your Input format here>", Locale.US)
DateFormat targetFormat = new SimpleDateFormat("<Your desired format here>", Locale.US)
Date Fdate = originalFormat.parse(date)
formattedDate = targetFormat.format(Fdate)
public static String formatDate(String fromFormat, String toFormat, String dateToFormat) {
SimpleDateFormat inFormat = new SimpleDateFormat(fromFormat);
Date date = null;
try {
date = inFormat.parse(dateToFormat);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat outFormat = new SimpleDateFormat(toFormat);
return outFormat.format(date);
}
Use:
formatDate("dd-MM-yyyy", "EEEE, dd MMMM yyyy","26-07-2019");
Result:
Friday, 26 July 2019

ParseException when parse date via SimpleDateFormat

I'm trying to parse date from string to Date
My string date is: Fri Apr 30 01:20:29 +0700 2010
My code is:
SimpleDateFormat format = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = format.parse(input);
But i'm getting an Unparsable date exception.
What's wrong?
Check your format, you only have one E instead of three :
EEE MMM dd HH:mm:ss Z yyyy
EDIT : also check your JVM's language locale or specify one for your call.
As writen in comments, following code works :
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);

java.text.ParseException: Unparseable date Exception while converting timestamp value to time in java

I want to convert a Timestamp value which is passed as String to SimpleDateFormat Object into Time Value but it throws a Unparseable date exception.
The Value which i am passing is Thu Jan 1 17:45:00 UTC+0530 1970
Bur i am getting an Exception as mentioned below:
java.text.ParseException: Unparseable date: "Thu Jan 1 17:45:00 UTC+0530 1970"
Please find the below code which i have implemented(Not Working):
static SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
static SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
static SimpleDateFormat outputFormatTime = new SimpleDateFormat("HH:mm:ss");
public static String convertUtcDateStringToTime(String utcDateValue) throws Exception
{
Date parsedDate = dateFormat.parse(utcDateValue);
String returnDate=outputFormatTime.format(inputFormat.parse(parsedDate.toString()));
return returnDate;
}
If i use the below code it works fine for me(Working) but its a depreciated function of Date which i want to avoid..
#SuppressWarnings("deprecation")
public static String convertUtcDateStringToTime(String utcDateValue) throws Exception
{
Date dateValue=new Date(utcDateValue);
Date parsedDate = dateFormat.parse(dateValue.toString());
String returnDate=outputFormatTime.format(inputFormat.parse(parsedDate.toString()));
return returnDate;
}
Please Guide Me To implement the logic where i have missed. Thanks in advance.
with an addition to the answers if the formatting string is like this
"EEE MMM dd HH:mm:ss z yyyy"
then your input string should be
"Thu Jan 1 17:45:00 +0530 1970"
note that the "UTC" is skipped as implicitly it refers to the RFC 822 time zone
First of all, your 2nd SimpleDateFormat object, is not needed at all. You are doing the extra work, which is not needed. So, remove this variable:
static SimpleDateFormat inputFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US); // Not needed.
Secondly DateFormat#format(Date) methods takes a Date object. You are passing it a String. That wouldn't work. That is why you don't need the above object. There is no need to do a inputFormat.parse(parsedDate.toString()) again.
Now, the format to parse your current string should be:
"EEE MMM dd HH:mm:ss 'UTC'z yyyy"
You need to give the UTC in quotes, before z. Or for more general case:
"EEE MMM dd HH:mm:ss zZ yyyy"
So, your code should be like:
static SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zZ yyyy", Locale.US);
static SimpleDateFormat outputFormatTime = new SimpleDateFormat("HH:mm:ss");
public static String convertUtcDateStringToTime(String utcDateValue) throws Exception
{
Date parsedDate = dateFormat.parse(utcDateValue);
String returnDate=outputFormatTime.format(inputFormat);
return returnDate;
}
You input dateformat needs to be
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zZ yyyy", Locale.US);
The other formatting is all upto, you based on your requirements.

Java:Date format conversion issue

I have a date of the format EEE MMM dd HH:mm:ss zzz yyyy
I have to convert this to dd/MM/yyyy
I did the following:
SimpleDateFormat fmt = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
SimpleDateFormat fmtddMMyyyy = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date d = fmt.parse("Mon May 28 00:00:00 IST 2012");<br>
String formattedDate = fmtddMMyyyy.format(d);
When I tried to print d it displays 0027833001988071567.
Where am I going wrong?
I have to guess that your real code is only marginally connected to what you show. Due to some experiments and the documentation.
Possibly the original parsing throws an exception and what every you print has nothing to do with you date manipulation.
In order to fix the problem
print the string you want to convert
print the parsed date
print the converted String
Use the constructor variants with Locale argument so everybody on stackoverflow can reproduce it, and you application works the same wherever it is running.
All this in a simple class containing nothing but a main method which contains the code.
If the problem persists, come back with the code and its output.
With my advice partially applied you might end with this:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class Experiment {
public static void main(String args[]) throws ParseException {
SimpleDateFormat fmt = new SimpleDateFormat(
"EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
SimpleDateFormat fmtddMMyyyy = new SimpleDateFormat("dd/MM/yyyy",
Locale.US);
java.util.Date d = fmt.parse("Mon May 28 00:00:00 IST 2012");
String formattedDate = fmtddMMyyyy.format(d);
System.out.println(formattedDate);
}
}
Which prints out
28/05/2012
try:
String formattedDate = fmtddMMyyyy.format(d);
UPD: Well I got the following solution:
SimpleDateFormat fmt = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
works fine (without locale defining wasn't working for me too). Because you define the month name and day-of-week name according to English language, not your local, as I presume.

Categories

Resources