Converting String Format Date for Date Object - java

I am getting a Date format in String as Output like this.
Fri May 18 00:00:00 EDT 2012
I need to Convert this to a Date Object. What approach shall I use?
Thank you.
This is the program i used.
import java.util.*;
import java.text.*;
public class DateToString {
public static void main(String[] args) {
try {
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss 'EDT' yyyy ");
date = (Date)formatter.parse("Fri May 18 00:00:00 EDT 2012");
String s = formatter.format(date);
System.out.println("Today is " + s);
} catch (ParseException e) {
System.out.println("Exception :"+e);
}
}
}

Have a look at: java.text.SimpleDateFormat Java API
SimpleDateFormat dateParser = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy",
Locale.US);
Date date = dateParser.parse("Fri May 18 00:00:00 EDT 2012");
Update: note to self, locale can be important.

Use SimpleDateFormat and implementations to get a date displayable in a format you want.
Example:
String myDateString = "Fri May 18 00:00:00 EDT 2012";
SimpleDateFormat dateFormat = new SimpleDateFormat();
dateFormat.applyPattern( "EEE MMM dd HH:mm:ss z yyyy" );
try {
Date d = dateFormat.parse( myDateString );
System.out.println( d ); // Fri May 18 00:00:00 EDT 2012
String datePattern1 = "yyyy-MM-dd";
dateFormat.applyPattern( datePattern1 );
System.out.println( dateFormat.format( d ) ); // 2012-05-18
String datePattern2 = "yyyy.MM.dd G 'at' HH:mm:ss z";
dateFormat.applyPattern( datePattern2 );
System.out.println( dateFormat.format( d ) ); // 2012.05.18 AD at 00:00:00 EDT
String datePattern3 = "yyyy.MM.dd G 'at' HH:mm:ss Z";
dateFormat.applyPattern( datePattern3 );
System.out.println( dateFormat.format( d ) ); // 2012.05.18 AD at 00:00:00 -400
}
catch ( Exception e ) { // ParseException
e.printStackTrace();
}

Use SimpleDateFormat with the following pattern:
EEE MMM dd HH:mm:ss 'EDT' YYYY
This doesn't worry about Timezone, Alternatively, with timezone inclusion: (untested) EEE MMM dd HH:mm:ss z YYYY (it's a lowercase z). Bear in mind, I haven't tested it yet (as I'm on my way home from work).

Related

How do I convert this time format into epoch in java? "Tue Dec 28 16:55:00 GMT+05:30 2021" to Epoch

I am using 'Single Date and Time Picker' Library in my Android Project but it only returns date and time in the below mentioned format.
"Tue Dec 28 16:55:00 GMT+05:30 2021"
I want to convert this into epoch time format.
Library:
https://github.com/florent37/SingleDateAndTimePicker
Alternative solution with java.time.OffsetDateTime
Here's an alternative solution that makes use of java.time keeping all the information of the input String:
public static void main(String[] args) throws IOException {
// input
String dpDate = "Tue Dec 28 16:55:00 GMT+05:30 2021";
// define a formatter with the pattern and locale of the input
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(
"EEE MMM dd HH:mm:ss OOOO uuuu", Locale.ENGLISH);
// parse the input to an OffsetDateTime using the formatter
OffsetDateTime odt = OffsetDateTime.parse(dpDate, dtf);
// receive the moment in time represented by the OffsetDateTime
Instant instant = odt.toInstant();
// extract its epoch millis
long epochMillis = instant.toEpochMilli();
// and the epoch seconds
long epochSeconds = instant.getEpochSecond();
// and print all the values
System.out.println(String.format("%s ---> %d (ms), %d (s)",
odt, epochMillis, epochSeconds));
}
Output:
2021-12-28T16:55+05:30 ---> 1640690700000 (ms), 1640690700 (s)
A LocalDateTime should not be used here, because you may lose the information about the offset and a ZonedDateTime can neither be used due to the input lacking information about a zone like "Asia/Kolkata" or "America/Chicago", it just provides an offset from UTC.
If you simply want to get the epoch millis, you can write a short method:
// define a constant formatter in the desired class
private static final DateTimeFormatter DTF_INPUT =
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(
"EEE MMM dd HH:mm:ss OOOO uuuu", Locale.ENGLISH);
…
/**
* parses the input, converts to an instant and returns the millis
*/
public static long getEpochMillisFrom(String input) {
return OffsetDateTime.parse(input, DTF_INPUT)
.toInstant()
.toEpochMilli();
}
The format for your date is EEE MMM dd HH:mm:ss zzzz yyyy
String date = "Tue Dec 28 16:55:00 GMT+05:30 2021";
try {
val sdf = SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy")
val mDate = sdf.parse(date)
val epochTime = TimeUnit.MILLISECONDS.toSeconds(mDate.time)
} catch (e: ParseException) {
e.printStackTrace()
}
Variable epochTime will have the seconds stored in it.
To convert it back to a format you can do -
val sdf = SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy")
sdf.format(epochTime)
Latest Java 8 Requires Min Api Level 26
String date = "Tue Dec 28 16:55:00 GMT+05:30 2021";
DateTimeFormatter format = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzzz yyyy");
LocalDateTime parsedDate = LocalDateTime.parse(date, format);
val milliSeconds = parsedDate.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
By Following Ansari's Answer, I did this to convert it into Epoch
SimpleDateFormat sdf3 = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzzz yyyy", Locale.ENGLISH);
Date d1 = null;
try{
d1 = sdf3.parse("Tue Dec 28 16:55:00 GMT+05:30 2021");
epochTime = TimeUnit.MILLISECONDS.toSeconds(d1.getTime());
Log.e("epoch time", "onDateSelected: "+epochTime );
}
catch (Exception e){ e.printStackTrace(); }

Formatting date with time zone. Wrong format

I have tried many different types of solutions using java.text.SimpleDateFormat but couldn't quite get it right.
The input string I receive is Tue Nov 5 00:00:00 UTC+0530 2013.
The format that I want is dd-MMM-yy.
Below is the code that I use:
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM d HH:mm:ss zZ yyyy", Locale.ENGLISH);
date = formatter.parse(s);
System.out.println(date);
I receive an error: unreported exception ParseException; must be caught or declared to be thrown
date = formatter.parse(s);
I tried a lot of change in my formats but still I receive this error. Can anyone please let me know the exact format of the string that I am passing?
Handle Exceptions
You have not handled exceptions in your code. That is why the compiler gives errors. You need to handle the ParseException that may be thrown during parsing.
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM d HH:mm:ss zZ yyyy", Locale.ENGLISH);
try{
date = formatter.parse(s);
System.out.println(date);
}catch(ParseException ex){
//exception
ex.printStackTrace();
}
Or you can add throws ParseException to your method .
According to your comment it seems to be you are trying to convert a date[String] to another format. If I am correct then the following example may help you.
String inputstring="Tue Nov 5 00:00:00 UTC+0530 2013";
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM d HH:mm:ss zZ yyyy", Locale.ENGLISH);
DateFormat outformat = new SimpleDateFormat("dd-MMM-yy");
try {
String result = outformat.format(formatter.parse(inputstring));
System.out.println(result);
} catch (ParseException ex) {
ex.printStackTrace();
}
Output:
04-Nov-13
No Problem
Your code works* if you catch the exception as directed in the correct answer.
String input = "Tue Nov 5 00:00:00 UTC+0530 2013";
java.text.SimpleDateFormat sdformatter = new java.text.SimpleDateFormat( "EEE MMM d HH:mm:ss zZ yyyy" , Locale.ENGLISH );
java.util.Date date = null;
try {
date = sdformatter.parse( input );
} catch ( ParseException ex ) {
System.out.println( "ERROR: " + ex ); // … handle exception
}
System.out.println( "date: " + date + " (adjusted to Kolkata time via Joda-Time: " + new DateTime( date , DateTimeZone.forID( "Asia/Kolkata" ) ) );
When run.
date: Mon Nov 04 10:30:00 PST 2013 (adjusted to Kolkata time via Joda-Time: 2013-11-05T00:00:00.000+05:30
Joda-Time
That same format works in Joda-Time 2.5.
The java.util.Date/.Calendar/java.text.SimpleDateFormat classes bundled with Java are notoriously troublesome, confusing, and flawed. Avoid them. Use either Joda-Time or the new java.time package built into Java 8 (inspired by Joda-Time).
String input = "Tue Nov 5 00:00:00 UTC+0530 2013";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "EEE MMM d HH:mm:ss zZ yyyy" );
DateTime dateTime = formatter.parseDateTime( input ).withZone( DateTimeZone.forID( "Asia/Kolkata" ) );
System.out.println( "dateTime: " + dateTime );
When run.
dateTime: 2013-11-05T00:00:00.000+05:30
Alternate Format
In your case, you could ignore the UTC as it is redundant with the offset ( +0530 ). An offset is assumed to be from UTC. You can ignore characters by using quote marks.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "EEE MMM d HH:mm:ss 'UTC'Z yyyy" );
*Your code works for me using Java 8 Update 25. Earlier versions of java.text.SimpleDateFormat had varying behaviors with the Z-letter and offsets. But, again, you should not even be using SimpleDateFormat.

Trouble parsing Java Date Object?

I am receiving a Java Date formatted like so: "Sun Sep 14 02:00:00 PDT 2014" into a yyyy-MM-dd format but I can't seem to parse it. What I tried is the following:
String time = "Sun Sep 14 02:00:00 PDT 2014";
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
Date contractEffectiveDateFormat = f.parse(time);
System.out.println("Date: " + contractEffectiveDateFormat);
However, I get an error saying that this date is unparsable. I'm not sure how to go about parsing this date because if I try to parse the date using the following:
DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy");
which is how to actually parse the date correctly into a Date object,
the string would turn into a Date object, but I can't seem to do anything with it from there. I want to turn it in so that it looks like 2014-09-14. Any ideas on how to do so? Thanks!
Use two DateFormat(s) one for input and for output,
String time = "Sun Sep 14 02:00:00 PDT 2014";
DateFormat out = new SimpleDateFormat("yyyy-MM-dd");
DateFormat in = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy");
try {
Date effectiveDate = in.parse(time);
System.out.println("Date: " + out.format(effectiveDate));
} catch (ParseException e) {
e.printStackTrace();
}
Output is the requested
Date: 2014-09-14
Your incoming string is this String time = "Sun Sep 14 02:00:00 PDT 2014";
which means the SimpleDateFormat pattern should match the incoming String pattern so you need to use SimpleDateFormat like this
DateFormat inFormat=new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy",Locale.ENGLISH);
Then when you called parse() on inFormat it will give you Date Object which doesnot have particular format associated with it. So in order to format the Date again you need to create SimpleDateFormat object specifying the format you want which is this
DateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Ultimately bind all together
One more thing always specify the Locale
String time = "Sun Sep 14 02:00:00 PDT 2014";
DateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
// good practice to specify the locale
DateFormat inFormat=new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy",Locale.ENGLISH);
try {
Date parsedDate = inFormat.parse(time);
System.out.println("Required Formatted Date: " + outFormat.format(effectiveDate));
} catch (ParseException e) {
e.printStackTrace();
}
Simply add another SimpleDateFormat that'll allow you to present the Date object the way you want:
public static void main(String[] args) throws ParseException {
String time = "Sun Sep 14 02:00:00 PDT 2014";
DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy");
Date contractEffectiveDateFormat = df.parse(time);
System.out.println("Date: " + contractEffectiveDateFormat);
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(f.format(contractEffectiveDateFormat)); // prints 2014-09-14
}

Java how to pass the timeformat in java "Fri Jan 24 12:22:13 +0000 2014"

I have got the following created date "Fri Jan 24 12:22:13 +0000 2014" from twitter , but when it comes to parsing , the goes to unparsable exception error at "z"
Would you please tell em what is the correct time format ?
The below is my code
String dateString = fullS.substring(0, 11) + " "+ year;
String timeZoneHK = content.getTimeZone();
SimpleDateFormat inputDf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
SimpleDateFormat outputDf = new SimpleDateFormat("HH:mm:ss EEE MMM dd yyyy");
Date date;
try {
TimeZone timezone = null;
date = inputDf.parse(dateString);
if(timeZoneHK.equals("Hong Kong")){
timezone = TimeZone.getTimeZone("Asia/Hong_Kong");
}
outputDf.setTimeZone(timezone);
String result =outputDf.format(date);
//System.out.println(outputDf.format(date));
viewHolder.txtDate.setText(result);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Exception
01-24 22:10:30.061: W/System.err(12573): java.text.ParseException: Unparseable date: "Fri Jan 24 13:37:08 +0000 2014" (at offset 0)
Use complete date String "Fri Jan 24 12:22:13 +0000 2014" if wanted to apply the specified format. And change z to Z:
SimpleDateFormat inputDf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
Refer to: SimpleDateFormat
Z - time zone (RFC 822) - (Time Zone) Z/ZZ/ZZZ:-0800 - ZZZZ:GMT-08:00 ZZZZZ:-08:00
Joda-Time
This kind of work is much easier with the third-party open-source date-time library, Joda-Time.
Here is some example code using Joda-Time 2.3.
String input = "Fri Jan 24 12:22:13 +0000 2014";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "EEE MMM dd HH:mm:ss Z yyyy" );
// Parse as UTC/GMT (no time zone offset) so we may conveniently compare to input.
DateTime dateTimeUtc = formatter.withZone( DateTimeZone.UTC ).parseDateTime( input );
// Convert to Hong Kong time zone.
DateTime dateTimeHongKong = dateTimeUtc.toDateTime( DateTimeZone.forID( "Asia/Hong_Kong" ) );
Dump to console…
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeHongKong: " + dateTimeHongKong );
When run…
dateTimeUtc: 2014-01-24T12:22:13.000Z
dateTimeHongKong: 2014-01-24T20:22:13.000+08:00
Back To Date
If you need a java.util.Date for other purposes, convert your DateTime.
java.util.Date date = dateTime.toDate();

Convert String into dateTime

I have to strings like this
Thu Oct 03 07:47:22 2013
Mon Jul 05 08:47:22 2013
I want to compare these dates, I am using SimpleDateFormat("EEE MMM dd HH:mm:ss yyy") but it gives me an exception : java.text.ParseException: Unparseable date:
Please help me to solve this problem!
You're missing an y for year:
EEE MMM dd HH:mm:ss yyyy
but you should use a more robust library, org.jodatime.
import org.joda.time.format.DateTimeFormat;
import org.joda.time.DateTime;
DateTimeFormat format = DateTimeFormat.forPattern("EEE MMM dd HH::mm:ss yyyy");
DateTime time = format.parseDateTime("Thu Oct 03 07:47:22 2013");
You missed a y in the format. 4 y were required for the year(though it may work fine with yyy, its better to use yyyy as it'll make your format more readable to others). And to get the DateTime object, you can use the Date object which you get by parsing the String to construct your DateTime.
Try something like this:-
String str = "Thu Oct 03 07:47:22 2013";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy"); // You missed a y here.
try {
Date d = sdf.parse(str);
DateTime dt = new DateTime(d.getTime()); // Your DateTime Object.
} catch (ParseException e) {
// Parse Exception
}
try with this method
public static Date formatStringToDate(String strDate) throws ModuleException {
Date dtReturn = null;
if (strDate != null && !strDate.equals("")) {
int date = Integer.parseInt(strDate.substring(0, 2));
int month = Integer.parseInt(strDate.substring(3, 5));
int year = Integer.parseInt(strDate.substring(6, 10));
Calendar validDate = new GregorianCalendar(year, month - 1, date);
dtReturn = new Date(validDate.getTime().getTime());
}
return dtReturn;
}

Categories