Java - Parsing a Date from a String - java

I want to parse a java.util.Date from a String. I tried the following code but got unexpected output:
Date getDate() {
Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd");
try {
date = sdf.parse("Sat May 11");
} catch (ParseException ex) {
Logger.getLogger(URLExtractor.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
return date;
}
When I run the above code, I got the following output:
Mon May 11 00:00:00 IST 1970

You have not specified a year in your string. The default year is 1970. And in 1970 the 11th of May was a Monday - SimpleDateFormat is simply ignoring the weekday in your string.
From the javadoc of DateFormat:
The date is represented as a Date object or
as the milliseconds since January 1, 1970, 00:00:00 GMT.

Specify a year within the Format to get the correct output.
If you don't specify any year, the default is 1970.

if the year is the problem you can add y for year:
public Date getDate() {
Date date = null;
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd y");
try {
date = sdf.parse("May 11 2010");
} catch (ParseException ex) {
Logger.getLogger(URLExtractor.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
return date;
}
System.out.println(getDate());
Tue May 11 00:00:00 EDT 2010
Edit:
To get the correct day of the week you need to specify the date (with the year). I edited the code above.

Related

Android time conversion

i have done code below to change time from UTC to another time zone but code is showing only UTC time.Also after formatting to source time format it shows system time zone .
private String setTimezone(String time){
sourceformatter = new SimpleDateFormat("hh:mm a, E dd MMM yyyy");
dateFormatter = new SimpleDateFormat("hh:mm a");
sourceformatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Log.e("reicievedformat",time);
Date value = null;
try {
value = sourceformatter.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
Log.d("afterfirstformat",dateFormatter.format(value));
dateFormatter.setTimeZone(TimeZone.getTimeZone("IST"));
time =dateFormatter.format(value);
Log.d("Finaltime",time);
return time;
}
Output:- Log values
E/reicievedformat: 12:36 PM, Mon 08 Oct 2018
D/afterfirstformat: 06:21 PM
D/Finaltime: 12:36 PM
As you can see I'm getting 12:36 PM, Mon 08 Oct 2018 ("UTC") and I want to convert to IST, but the final time, 12:36 PM, doesn’t seem to have been converted.
IST in java stands for "Israel Standard Time".
Use this for "Indian Standard Time"
dateFormatter.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
The date & time APIs in Java gives you headache.
I use this library by Daniel Lew.
https://github.com/dlew/joda-time-android
Try this
public static String getDateOut(String ourDate) {
try
{
//be sure that passing date has same format as formatter
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm a, E dd MMM yyyy");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = formatter.parse(ourDate);
SimpleDateFormat dateFormatter = new SimpleDateFormat("hh:mm a"); //this format changeable
dateFormatter.setTimeZone(TimeZone.getTimeZone("IST"));
ourDate = dateFormatter.format(value);
}
catch (Exception e)
{
ourDate = "00-00-0000 00:00";
}
return ourDate;
}

Convert UTC Date to local Date

I am converting from epoch time (which is in UTC) to a format as shown below. Now I tried different SO answers to convert UTCDate from UTC to local time. But I am not getting the local time.
Any help would be appreciated.
String epochTime = "1436831775043";
Date UTCDate = new Date(Long.parseLong(epochTime));
Date localDate; // How to get this?
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
String result = simpleDateFormat.format(UTCDate);
Also, the conversion has to be done without the help of any external library.
Java 8
String epochTime = "1436831775043";
Instant utcInstant = new Date(Long.parseLong(epochTime)).toInstant();
ZonedDateTime there = ZonedDateTime.ofInstant(utcInstant, ZoneId.of("UTC"));
System.out.println(utcInstant);
LocalDateTime here = there.withZoneSameInstant(ZoneId.systemDefault()).toLocalDateTime();
System.out.println(here);
Which outputs:
2015-07-13T23:56:15.043Z
2015-07-14T09:56:15.043
After thoughts...
I think you're chasing your tail. Date is just a container for the number of milliseconds since the epoch (January 1, 1970, 00:00:00 GMT). It doesn't internally carry a representation of a time zone (AFAIK).
For example...
String epochTime = "1436831775043";
Date UTCDate = new Date(Long.parseLong(epochTime));
// Prints the "representation" of the Date
System.out.println(UTCDate);
// Local date/time format...
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy h:mm:ss a");
try {
System.out.println("local format: " + simpleDateFormat.format(UTCDate));
System.out.println("local Date: " + simpleDateFormat.parse(simpleDateFormat.format(UTCDate)));
} catch (ParseException ex) {
Logger.getLogger(JavaApplication203.class.getName()).log(Level.SEVERE, null, ex);
}
// UTC date/time format
try {
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("utc format: " + simpleDateFormat.format(UTCDate));
System.out.println("utc date: " + simpleDateFormat.parse(simpleDateFormat.format(UTCDate)));
} catch (ParseException ex) {
Logger.getLogger(JavaApplication203.class.getName()).log(Level.SEVERE, null, ex);
}
Which outputs...
Tue Jul 14 09:56:15 EST 2015
local format: 14/07/2015 9:56:15 AM
local Date: Tue Jul 14 09:56:15 EST 2015
utc format: 13/07/2015 11:56:15 PM
utc date: Tue Jul 14 09:56:15 EST 2015
If you have a look at local Date and utc date they are the same thing, even though the local format and utc format are formatted correctly.
So, instead of chasing your tale trying to get Date to "represent" a value you want, either use Java 8's Time API or JodaTime to manage the Time Zone information or simply format the Date into the Time Zone you want...
Further, if we do something like...
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy h:mm:ss a");
Date localDate = simpleDateFormat.parse(simpleDateFormat.format(UTCDate));
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date utcDate = simpleDateFormat.parse(simpleDateFormat.format(UTCDate));
System.out.println(localDate.getTime());
System.out.println(utcDate.getTime());
System.out.println(localDate.equals(utcDate));
It will print...
1436831775000
1436831775000
true
You can set your time zone in the formatter:
simpleDateFormat.setTimeZone(TimeZone.getDefault());

Issue with parsing Date string

I'm trying to parse the following string to a Date object:
2013-12-26T01:00:56.664Z
Using this SimpleDateFormat:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
But I'm getting a:
java.text.ParseException: Unparseable date: "2013-12-26T01:00:56.664Z" (at offset 19)
What am I doing wrong, How I should handle the T and the Z letters in the date?
The real isssue with the date is not T & Z but the milliseconds.
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" This must be the format that is to be used becaue there are milli seconds as well in the input date.
You can use this
String date = "2013-12-26T01:00:56.664Z";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
try {
System.out.println(sdf.parse(date)); // Result Thu Dec 26 01:00:56 CET 2013
} catch (ParseException e) {
e.printStackTrace();
}

Java date object returning 30 as the month?

Why is this code giving me trouble?
public Date setupDate(){
String startDateString ="05/10/2010 04:30:20";
SimpleDateFormat df = new SimpleDateFormat("mm/dd/yyyy HH:mm:ss");
Date startDate = null;
try {
startDate = df.parse(startDateString);
String newDateString = df.format(startDate);
System.err.println(newDateString);
System.err.println(startDate.toString());
} catch (ParseException e) {
e.printStackTrace();
}
return startDate;
}
output:
SEVERE: 30/10/2010 04:30:20
SEVERE: Sun Jan 10 04:30:20 EST 2010
I expected May 10 of course, not January(I don't know how it became January, or the 30.
Read the section Date and Time Patterns
You should use
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
M is for Month in year while m is for minute in hour
The format symbol for month uses capital M; you've used minutes m twice, which is 30 here. For reference, here's the Javadocs that explain all format symbols for SimpleDateFormat.

Get correct long value from parsed Date (Timezone issue)

I'm trying to parse a date from a String and get the long value. The long value will be later sent to an SQL query.
here's my code:
String dayDate = "28-02-2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date day = new Date();
try {
day = sdf.parse(dayDate);
} catch (ParseException pe) {
pe.printStackTrace();
}
System.out.println("day : "+day.toString()+ " long : " + day.getTime());
which gives the following output:
day : Thu Feb 28 00:00:00 EET 2013 long : 1362002400000
which is correct but not what I want since the long value results in Wed, 27 Feb 2013 22:00:00 GMT (http://www.epochconverter.com/) (I'm in a GMT+2 timezone). And i need to send to correct long value to sql.
Is there anyway to work around this without using external libraries?
SimpleDateFormat is locale-aware, meaning the date it parses is in your timezone. Midnight 28 Feb in GMT+2 is actually 10pm 27 Feb in GMT, the long value 1362002400000. I would add this to get the parsing right (would't bother using Calendar):
sdf.setTimeZone(TimeZone.getTimeZone("GMT"))
Again, when you print this date it uses SimpleDateFormat and that's why you can see EET in the output.
Passing this to database is a different story though once you get this right.
Use DateFormat.setCalendar(Calendar cal) to set a Calendar with GMT as its timezone, or use DateFormat.setTimeZone(TimeZone zone) with the GMT TimeZone. That will ensure that the resulting Date will be 00:00:00 in GMT instead of in EET.
If you add a timezone specifier to your string you can force java to use GMT for the conversion:
String dayDate = "28-02-2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy z"); // z is a timezone specifier
Date day = new Date();
try {
day = sdf.parse(dayDate + " GMT"); // Use GMT timezone.
} catch (ParseException pe) {
pe.printStackTrace();
}
System.out.println("day : "+day.toString()+ " long : " + day.getTime());
You are converting between text and internal (Date) representations of dates and times without explicitly stating the time-zone. That never goes well.
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
Date date = calendar.getTime();
Use your timezone String:
TimeZones

Categories