I have a requirement, where I need to override the date
when I parse time(hh:mm:ss) using SimpleDateFormat, what i get is object of date (Thu Jan 01 hh:mm:ss IST 1970)
i want to overide epoch date with today date(without time).
is there a api or method in joda/jdk, which can do this for me
Basically, you can't, but what you can do, is merge the values from the "time" conversion with another date (like today)...for example
try {
Date date = new SimpleDateFormat("hh:mm:ss").parse("13:30:51");
System.out.println(date);
Calendar time = Calendar.getInstance();
time.setTime(date);
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, time.get(Calendar.HOUR_OF_DAY));
today.set(Calendar.MINUTE, time.get(Calendar.MINUTE));
today.set(Calendar.SECOND, time.get(Calendar.SECOND));
System.out.println(today.getTime());
} catch (ParseException ex) {
ex.printStackTrace();
}
There's probably a really fancy way of doing this with less code, but I was trying to avoid deprecated methods.
For me, this outputs...
Thu Jan 01 13:30:51 EST 1970
Thu Oct 31 13:30:51 EST 2013
Beware though, this does not reset the milliseconds value of the today Calendar, in case that's important...
Related
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());
I have the method
public static void testDateFormat() throws ParseException {
DateFormat dateFormat=new SimpleDateFormat("HH:mm:ss");
Date hora;
hora=dateFormat.parse("00:00:01");
System.out.println(hora.getHours()+" "+hora.getMinutes());
System.out.println("Date "+hora);
System.out.println("Seconds "+TimeUnit.MILLISECONDS.toSeconds(hora.getTime()));
}
The output is
0 0
Date Thu Jan 01 00:00:01 COT 1970
Seconds 18001
Why the number of seconds is 18001? I expected to get 1 second.
Because your Date has a TimeZone that is not UTC. It is, in fact, COT - which is UTC-5. And 5*60*60 is 18000 (or your result, plus one second). To get the value you expect, you could call DateFormat#setTimeZone(TimeZone) like,
DateFormat dateFormat=new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); // <-- Add this.
Date hora=dateFormat.parse("00:00:01");
System.out.println(hora.getHours()+" "+hora.getMinutes());
System.out.println("Date "+hora);
System.out.println("Seconds "+TimeUnit.MILLISECONDS.toSeconds(hora.getTime()));
Output is as you expect.
Edit
As noted in the comments, Date#getTime() per the Javadoc
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
And your Date of
Thu Jan 01 00:00:01 COT 1970
is equivalent to
Thu Jan 01 00:05:01 UTC 1970
and thus you get the 5 hour difference.
The answer by Elliott Frisch is correct.
Time-Only
But if you are working with time-only without date or time zone, then use a date-time library that can handle that explicitly rather than hacking the java.util.Date class.
LocalTime
Use either the Joda-Time library or the java.time package in Java 8. Both offer a LocalTime class.
LocalTime localTime = LocalTime.parse( "00:00:01" );
int minuteOfHour = localTime.getMinuteOfHour();
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
I have a time input in the following format from a RSS feed:
Wed Jun 13 17:05:44 +0000 2012
and I need output as Wed Jun 13, 2012 22:35:44
The source time will be always in GMT, and the required output time will be in the device time zone(it may be GMT+5:30 or GMT-2:00 or any).
So firstly I have an calendar instance with GMT, as follows.
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Then modified the calendar like following using StringTokenizer on input time.
calendar.set(Calendar.DAY_OF_MONTH, date);
calendar.set(Calendar.MONTH, month);
.
.
etc.
Next I have the following code:
calendar.setTimeZone(TimeZone.getDefault());
Basically the above code changes a calendar into device time zone.
Now the matter is the above code is working fine in normal environment, but not working in Android.
Any solution? Please help.
First you required DateFormat to parse string value in Date object and then you can set Timezone in Date as well as you can make Calendar object with help of Date that calendar object will be your device timezone instance.
Below code is working at my side
String input_format = "EEE MMMMM dd HH:mm:ss Z yyyy";
String input_value="Wed Jun 13 17:05:44 +0000 2012";
Date date=null;
SimpleDateFormat sdf = new SimpleDateFormat(input_format);
try {
date = sdf.parse(input_value);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = sdf.getCalendar();
calendar.setTime(date);
if i understand it right, you just want to set the timezome
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setTimeZone("Europe/Paris");
this for example set the timezone to Paris
I have the following Java:
DateFormat formatter = new SimpleDateFormat(
"EEE MMM dd yyyy HH:mm:ss zZ (zzzz)", Locale.ENGLISH);
Calendar cal = Calendar.getInstance();
cal.set(2011, Calendar.APRIL, 1);
out.println(formatter.format(cal.getTime()));
out.println();
Date date;
try {
date = formatter
.parse("Fri Apr 01 2011 00:00:00 GMT-0400 (Eastern Daylight Time)");
} catch (ParseException e) {
out.println("Failed to parse date: " + e.getMessage());
e.printStackTrace(out);
}
This is in a servlet, and the Calendar-constructed date comes out as:
Fri Apr 01 2011 16:42:24 EDT-0400 (Eastern Daylight Time)
This looks like the same format as the date string I'm trying to parse, except for EDT-0400 versus the desired GMT-0400. The code fails when trying to parse the date string:
java.text.ParseException: Unparseable date: "Fri Apr 01 2011 00:00:00 GMT-0400 (Eastern Daylight Time)"
How can I parse such a string? This is coming from a JavaScript date in a Sencha Touch 1.1.1 model, stored in WebSQL local storage.
For some reason GMT-0400 isnt' working, and UTC-0400 is working. You can replace GMT with UTC.
Note that this part will be completely ignored - the timezone will be resolved from what's found in the brackets (at least on my machine, JDK 6)
I debugged SimpleDateFormat and it seems that it will only parse GMT-04:00 but not GMT-0400.
It will accept UTC-0400, however it will throw away the hours/minutes modifier and will incorrectly parse it as UTC. (This happens with any other timezone designation, except for GMT)
It will also parse -0400 correctly, so the most robust solution is probably to simply remove GMT from your date string.
The upshot of the story is that SimpleDateFormat is anything but simple.
Update: Another lesson is that I could've saved a lot of time by passing a ParsePosition object to the parse() method:
DateFormat formatter = new SimpleDateFormat(
"EEE MMM dd yyyy HH:mm:ss zzzz", Locale.ENGLISH);
Date date;
ParsePosition pos = new ParsePosition( 0 );
date = formatter
.parse("Fri Apr 01 2011 00:00:00 UTC-0400", pos);
System.out.println( pos.getIndex() );
Will print out 28, indicating that the parsing ended at character index 28, just after UTC.