Calendar getTime() only returns EST - java

Calendar cl = Calendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles"));
cl.setTimeInMillis(time);
Toast.makeText(getActivity(), cl.getTime().toString(), Toast.LENGTH_LONG).show();
What ever time I put it always returns the time in EST. I want it to return the time in PST. Does anyone know that could posibly be wrong?
P.S.
My local time is EST.

Try this:
TimeZone.setDefault(TimeZone.getTimeZone("PST"));
Calendar cl = Calendar.getInstance();

This isn't really an answer but it's too big to put into a comment. This is what I found.
My test looked like this
TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
Calendar cl = Calendar.getInstance(tz);
System.out.println(tz.getDisplayName());
String dayname = cl.getDisplayName(Calendar.DAY_OF_WEEK,Calendar.SHORT,Locale.US);
String monthname = cl.getDisplayName(Calendar.MONTH,Calendar.SHORT,Locale.US);
int hour = cl.get(Calendar.HOUR);
int min = cl.get(Calendar.MINUTE);
int sec = cl.get(Calendar.SECOND);
int mill = cl.get(Calendar.MILLISECOND);
int year = cl.get(Calendar.YEAR);
System.out.println("Time = " + cl.getTime().toString());
System.out.println("Manually = " +
dayname + " " + monthname + " " +
hour + ":" + min +":" + sec + ":" + mill + " " +
cl.getTimeZone().getDisplayName(Locale.US) + " " + year);
Which gave the output
Pacific Standard Time
Time = Tue Nov 05 11:36:33 EST 2013
Manually = Tue Nov 8:36:33:238 Pacific Standard Time 2013
Looking at Calendar.getTime():
public final Date getTime() {
return new Date(getTimeInMillis());
}
Following the bouncing ball...
public long getTimeInMillis() {
if (!isTimeSet) {
updateTime();
}
return time;
}
private void updateTime() {
computeTime();
// The areFieldsSet and areAllFieldsSet values are no longer
// controlled here (as of 1.5).
isTimeSet = true;
}
But I don't have the source for computTime() so that's where I stopped.
Gabriel's answer works, fwiw.

Calendar.getTime() returns a java Date instance which represents the number of milliseconds from the epoch January 1, 1970, 00:00:00 GMT. Calling toString() on a Date instance will print the date based on the timezone configured on the server. To properly format a date for output in another timezone, you'll want to look at using a date formatter.
TimeZone est = TimeZone.getTimeZone("America/New_York");
Calendar cal = Calendar.getInstance(est);
DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
formatter.setTimeZone(est);
System.out.println(formatter.format(cal.getTime()));

Related

Firebase - retrieving data from a date

I want to retrieve data from a particular date from Firebase. They are stored in the following format:
I am using a datePicker to choose a date. But I am not able to figure out how I can change the date chosen to the above format.
For example: I choose a date say 28th March 2018. I would use the code:
int day = datePicker.getDayOfMonth();
String month = datePicker.getMonth() + "";
String year = datePicker.getYear() + "";
But I am not able to figure out how to change it to the following format, Wed Mar 28 2018 00:00:00 GMT+530 (IST)
After spending hours, trying to figure out a way, I have finally found a solution and have realized that this was a pretty silly question to ask. Nevertheless, this is what I have come up with,
int day = datePicker.getDayOfMonth();
int year = datePicker.getYear();
int month = datePicker.getMonth() + 1;
try {
SimpleDateFormat sdf = new SimpleDateFormat("d-M-yyyy");
Date date = sdf.parse(day + "-" + month + "-" + year);
sdf = new SimpleDateFormat("EEE MMM dd yyyy");
String strDate = sdf.format(date) + " 00:00:00 GMT+0530 (IST)";
Log.d("date_simple", strDate);
} catch (ParseException e) {
Log.d("date_simple", e + "");
e.printStackTrace();
}

Java Joda time isAfter date solution

I want to compare two dates.
If the current date time is greater or after the
specific date , then it will return 'True'.
So far I have tried this.
String deadline = "25/11/2017 11:00:00";
DateTime utc = new DateTime(DateTimeZone.UTC);
DateTimeZone timeZone = DateTimeZone.forID("Asia/Dhaka");
DateTime dhakaTime = utc.toDateTime(timeZone);
//Dead Line Time
DateTimeFormatter format = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime deadlineTime = format.parseDateTime(deadline.trim());
//Comapare
return deadlineTime.isAfter(dhakaTime.plusDays(2));
As today is 23 and dhakaTime.plusDays(2) will be 25 so it should return
"true".
But I am getting "false".
Output value :
dhakaTime.plusDays(2) = 2017-11-25T14:10:27.762+06:00
deadlineTime = 2017-11-25T11:00:00.000+06:00
Am i missing something or doing something wrong?
It gives false correctly.
You're comparing
deadLineTime = 2017-11-25T11:00:00.000+06:00 and
dhakaTime(+2) = 2017-11-25T14:10:27.762+06:00
They both are at same date, but with time, deadLineTime is at 11AM but dhakaTime(+2) is at 2PM. So,
(Nov 25, 2017 11AM)isAfter(Nov 25, 2017 2PM) is false.
EDIT: Testcases
As you mentioned you're testing, The following used different test cases for comparing deadLine with dhakaTime (+1, and +2 days). I hope this gives you an idea about how this works.
public static void main(String[] args) {
String deadline = "25/11/2017 11:00:00";
DateTime utc = new DateTime(DateTimeZone.UTC);
DateTimeZone timeZone = DateTimeZone.forID("Asia/Dhaka");
DateTime dhakaTime = utc.toDateTime(timeZone);
//Dead Line Time
DateTimeFormatter format = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime deadlineTime = format.parseDateTime(deadline.trim());
System.out.println("Deadline : " + deadline);
System.out.println("Current datetim : " + dhakaTime);
System.out.println("current datetime + 1 day : " + dhakaTime.plusDays(1));
System.out.println("current datetime + 2 day : " + dhakaTime.plusDays(2));
System.out.println("Is deadline after current datetime:" + deadlineTime.isAfter(dhakaTime));
System.out.println("Is deadline after current datetime + 1 day:" + deadlineTime.isAfter(dhakaTime.plusDays(1)));
System.out.println("Is deadline after current datetime + 2 day:" + deadlineTime.isAfter(dhakaTime.plusDays(2)));
}
Try using the method DateTimeFormatter withZone(DateTimeZone zone) and use that to create the DateTime

Java date displays previous day , month and totally different year

I am trying to display Date based on timezone.
If I change my system time zone to US pacific time zone, today's date is displayed correctly. If I want to display 2000-01-01 output shows as 12/31/1969.
Can you please let me know if I have to make any change in system settings or java settings?.
Below is the example code:
package timezoneexample;
import java.text.DateFormat;
import java.util.Date;
import java.util.TimeZone;
public class TimezoneExample {
public static void main(String args[]) {
DateFormat dateFormat = null;
String datePattern = null;
char dateSeperator = '/';
try {
datePattern = "MM/dd/yyyy";
if (datePattern.length() <= 0)
throw new java.util.MissingResourceException(
"Didn't find date format", "", "");
boolean hasSeperatorAlready = false;
for (int i = 0; i < datePattern.length(); i++)
if (!Character.isLetter(datePattern.charAt(i)))
if (hasSeperatorAlready)
throw new java.util.MissingResourceException(
"Unvalid date format", "", "");
else
dateSeperator = datePattern.charAt(i);
} catch (java.util.MissingResourceException mre) {
System.out.println(mre);
}
dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
if (datePattern.length() > 0
&& dateFormat instanceof java.text.SimpleDateFormat) {
java.text.SimpleDateFormat sdf = (java.text.SimpleDateFormat) dateFormat;
sdf.applyPattern(datePattern);
}
dateFormat.setTimeZone(java.util.TimeZone.getDefault());
// enter DOB
Date dob = new Date(2000 - 01 - 01);
Date today = new Date();
String timeZone = System.getProperties().getProperty("user.timezone");
TimeZone tZone = TimeZone.getTimeZone(timeZone);
System.out.println("Timezone : " + tZone);
dateFormat.setTimeZone(tZone);
System.out.println("Date Of Birth : " + dateFormat.format(dob));
System.out.println("Date in Displayed as per Timezone : "
+ dateFormat.format(today));
}
}
Output:
Timezone : sun.util.calendar.ZoneInfo[id="America/Los_Angeles",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]]
Date Of Birth : 12/31/1969
Date in Displayed as per Timezone : 01/07/2015
Your error is here:
Date dob = new Date(2000 - 01 - 01);
This will be interpreted as:
Date dob = new Date(1998);
This will invoke the Date(long date) constructor, resulting in a date near 1970/01/01.
What you most probably want is:
Date dob = new Date(2000, 1, 1);
new Date(...) requires a long value, expressing the number of milliseconds since 1/1/1970. You're specifying 2000 - 1 - 1. This is NOT "year 2000, month 1 and day 1", it is a numeric expression equal to 1998 milliseconds.
To create a date based on year/month/day, use a Calendar:
Calendar c = Calendar.getInstance();
c.set(y, m-1 /* 0-based */, d); // e.g. c.set(2000, 0, 1);
return c.getTime();

How to compare item of set collection to current Date?

I have the following set and need to compare its date instance with the current date. Although both dates are the same but the comparison returns false !!
MyClass.java
import java.util.Date;
public class MyClass {
private Date date;
...
}
My Code
....
Set <MyClass> myclass = new HashSet();
I populate it with some data here...
for(MyClass m : myclass)
{
System.err.println("date>>:" + trim(m.getDate())); //returns 2013-08-08
System.err.println("date>>:" + trim(getCurrentDate())); //returns 2013-08-08
System.err.println("boolean:" +
trim(m.getDate()).equals(trim(getCurrentDate()))); //returns false
}
}
public Date getCurrentDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
dateFormat.format(date));
return date;
}
public Date trim(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR, 0);
return calendar.getTime();
}
Dates are not same, they may differ by millis/sec. Date equals doesn't depend upon format of date but compares value. Below code would return false as well:
Date d1 = new Date();
SimpleDateFormat f = new SimpleDateFormat("yyyy-mm-dd");
Date d2 = new Date();
f.format(d2);
System.out.println(d1);//e.g. Thu Aug 08 12:09:24 IST 2013
System.out.println(d2);//e.g. Thu Aug 08 12:09:26 IST 2013
System.out.println(d1.equals(d2));//false
Date.equals compares time (Date.getTime()), equals will return true only if they matches:
public boolean equals(Object obj) {
return obj instanceof Date && getTime() == ((Date) obj).getTime();
}
Per javadoc:
The result is true if and only if the argument is not null and is a Date object that represents the same point in time, to the millisecond, as this object.
Thus, two Date objects are equal if and only if the getTime method returns the same long value for both.
Date.getTime return the number of milliseconds since January 1, 1970, 00:00:00 GMT
So in you updated question with trim, consider you are comparing two long values of time in millis.
If you require to compare yyyy-MM-dd values of two different date instances, consider using String.equals instead (hack way):
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
String date1 = f.format(new Date());//2013-08-08
String date2 = f.format(new Date());//2013-08-08
System.out.println(date1.equals(date2));
Each time you call getCurrentDate, you might receive a new date. Formatting it the way you do is essentially a no-op and the date still carries its hours, minutes, seconds and milliseconds.
So they are actually proably different for real.
You could remove this extra information to get the desired behaviour.
The Date class includes the time of the day to millisecond precision, and the time counts when comparing for equality.
To compare only the "date" part you can do one of several things, for example format the dates as year-month-day and compare the resulting strings, or create Calendar objects from the dates and compare the year, month and day individually. Another option is to make sure the Dates you compare have the same hour of the day, for example 12:00, that way you can use the equals method.
You can use GregorianCalendar and Calendar#get(..) to only compare year, month, and day.
There is a perfect sample from the javadoc :
// get the supported ids for GMT-08:00 (Pacific Standard Time)
String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
// if no ids were returned, something is wrong. get out.
if (ids.length == 0)
System.exit(0);
// begin output
System.out.println("Current Time");
// create a Pacific Standard Time time zone
SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
// set up rules for Daylight Saving Time
pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
// create a GregorianCalendar with the Pacific Daylight time zone
// and the current date and time
Calendar calendar = new GregorianCalendar(pdt);
Date trialTime = new Date();
calendar.setTime(trialTime);
// print out a bunch of interesting things
System.out.println("ERA: " + calendar.get(Calendar.ERA));
System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
System.out.println("MONTH: " + calendar.get(Calendar.MONTH));
System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR));
System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH));
System.out.println("DATE: " + calendar.get(Calendar.DATE));
System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH));
System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR));
System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK));
System.out.println("DAY_OF_WEEK_IN_MONTH: "
+ calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM));
System.out.println("HOUR: " + calendar.get(Calendar.HOUR));
System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY));
System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND));
System.out.println("ZONE_OFFSET: "
+ (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000)));
System.out.println("DST_OFFSET: "
+ (calendar.get(Calendar.DST_OFFSET)/(60*60*1000)));
Actually there is a problem in your method..
public Date getCurrentDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
dateFormat.format(date);
return date;
}
dateFormat.format(date) will return a String date in yyyy-MM-dd format but you are returning date from this method which will return the Date in 'Thu Aug 08 12:21:34 IST 2013' this format not in '2013-08-08' this. So you should take the String as return from this method and then compare it by equals.
Try this, I think this should help you.

Time Zones in Java

I'm working on a security signature in java that also verifies the date and time the call is being made. The POST call arrives with something like
String date = "Sat, 27 Apr 2013 01:11:30 GMT"
SimpleDateFormat RFC1123Format = new SimpleDateFormat("EEE, dd MMM yyyyy HH:mm:ss z", Locale.US);
And I'm able to parse it
Calendar gmtTime = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
Date dateHeader = RFC1123Format.parse(date);
gmtTime.setTime(dateHeader);
System.out.println("Date Header (GMT TIME): " + gmtTime.getTimeInMillis() + " ms");
System.out.println("Hour of day (GMT TIME): " + gmtTime.get(Calendar.HOUR_OF_DAY));
Calendar currentTime = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
currentTime.setTimeInMillis(System.currentTimeMillis());
System.out.println("System Date (LA TIME): " + currentTime.getTimeInMillis() + " ms");
System.out.println("Hour of day (LA TIME): " + currentTime.get(Calendar.HOUR_OF_DAY));
currentTime.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("System Date (GMT TIME): " + currentTime.getTimeInMillis() + " ms");
System.out.println("Hour of day (GMT TIME): " + currentTime.get(Calendar.HOUR_OF_DAY));
System.out.println("Diff: " + Math.abs(gmtTime.getTimeInMillis() - currentTime.getTimeInMillis()));
However the printout I get differs by 1 entire hour.
Date Header (GMT TIME): 1367025090000 ms
Hour of day (GMT TIME): 1
System Date (LA TIME): 1367022298441 ms
Hour of day (LA TIME): 0
System Date (GMT TIME): 1367022298441 ms
Hour of day (GMT TIME): 0
Diff: 2791559
Any ideas?
You can use JodaTime >> http://joda-time.sourceforge.net/ that implements TimeZone Calculations more efficiently than Java calendar
You don't give your formatter the calendar that you are using to represent your timestamps.
In this case, your calendar is set to represent timestamps in GMT. GMT is a synonym for UTC and UTC never observes any adjustment for DST. Your formatter, however, by default must convert your supplied string with the system default calendar as the basis, which likely does observe DST.
If this is the case, you can get consistent reporting by making sure that your formatter is using the same calendar that you are using to represent your date/times. Try this:
SimpleDateFormat RFC1123Format = new SimpleDateFormat();
GregorianCalendar gc - new GregorianCalendar(TimeZone.getTimeZone("GMT"));
RFC1123Format.setCalendar(gc);
RFC1123Format.applyPattern("EEE, dd MMM yyyyy HH:mm:ss z");
gc.setTime(RFC1123Format.parse(yourDateString));
Fixed it myself by adding an extra verification to check if Daylight Savings is being observed. This is the final code:
Calendar gmtTime = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
Date dateHeader = RFC1123Format.parse(date);
gmtTime.setTime(dateHeader);
Calendar currentTime = Calendar.getInstance();
currentTime.setTimeInMillis(System.currentTimeMillis());
boolean DST = false;
if(currentTime.getTimeZone().inDaylightTime(currentTime.getTime())) {
DST = true;
}
currentTime.setTimeZone(TimeZone.getTimeZone("GMT"));
if(DST) {
currentTime.set(Calendar.HOUR_OF_DAY, currentTime.get(Calendar.HOUR_OF_DAY) + 1);
.
.
.
<code to handle last day of month and month change as a result of the hour adjustment>
}
Thanks #gangqinlaohu for your suggestion.

Categories

Resources