I've created a couple of subclasses of SimpleDateFormat to simplify dealing with an Azure feed I'm talking to on Android. One of them is as follows:
public class ISO8601TLDateFormat extends SimpleDateFormat {
private static String mISO8601T = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
public ISO8601TLDateFormat() {
super(mISO8601T);
}
public ISO8601TLDateFormat(Locale inLocale) {
super(mISO8601T, inLocale);
}
}
As you can see the intention is to produce or interpret dates looking like
2012-03-17T00:00:00.000+0100
which is what the Azure service is expecting. However, when I feed in Date objects constructed from a DatePicker thus:
mDate = new Date(mDatePicker.getYear(), mDatePicker.getMonth(), mDatePicker.getDayOfMonth());
the output of the ISO8601TLDateFormat is
3912-03-17T00:00:00.000+0100
As you can see, the year is 1900 more than I, or anyone else not from the future, would need. I've scrutinized the Date object on its entire journey to the Azure feed system and it reports its date is 2012, which is what I would have expected. Why is the SimpleDateFormat breaking?
The problem is that the constructors of Date do not receive what you expect. Taken from the java documentation:
public Date(int year,
int month,
int date)
Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).
Allocates a Date object and initializes it so that it represents midnight, local time, at the beginning of the day specified by the year, month, and date arguments.
Parameters:
year - the year minus 1900.
month - the month between 0-11.
date - the day of the month between 1-31.
You need to keep in mind that you construct a date with 0, 0, 1 being 1st of January 1900.
Related
I want to store date and time that user picks through date picker and time picker on Android. By reading various thread I came to conclusion to store date and time in INTEGER format. So I'm converting them to long values using following function but when I'm converting them back to Date it is giving me wrong Date.
private DatePickerDialog.OnDateSetListener startDatePickerListener = new DatePickerDialog.OnDateSetListener(){
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
String dateText = getTimeString(year,monthOfYear,dayOfMonth);
//Converting Date to long so that can be stored in DB
long date = Utility.getDateLong(year,monthOfYear,dayOfMonth);
taskModel.setStartDate(date);
startDateView.setText(dateText);
}
};
public static long getDateLong(int year, int month, int day){
Calendar cal = new GregorianCalendar(year, month, day);
long timeStamp = (cal.getTimeInMillis()+cal.getTimeZone().getOffset(cal.getTimeInMillis()))/1000;
return timeStamp;
}
To convert long value back to Date I'm using the below function :
public static String getDateFromLongValue(long d){
Date date = new Date(d);
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
String formattedDate = dateFormat.format(date);
return formattedDate;
}
But this is giving me the different date then the entered value. Is there any other way to do this. I basically need to compare dates and to find the time elapsed between two dates?
I suggest a duplicate because while "best way" is theoretically debatable, SQLite offers date functions based on the fact that SQLite doesn't have a time and date type, but does offer date functions based ISO-formatted TEXT timestamp.
One item that is definitely not a matter of opinion though is where you want to do the bulk of operations. You have two choices:
Query for a large amount of data then filter that in your app
Query for a subset of that data
You might will run into timing and memory issues if you don't pre-filter your dataset via the query (i.e. using date and time functions off an ISO-formatted text timestamp) and opt to transform epochs in Java.
I am using following code to convert timezone (GMT-3) to device local timezone.
int hour=17,minute=0,day=12,month=6,year=2014;
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-3"));
cal.set(year, (month-1), day,hour,minute);
cal.setTimeZone(TimeZone.getDefault());
Log.d("Time", cal.get(Calendar.DATE)+"/"+cal.get(Calendar.MONTH)+"/"+cal.get(Calendar.YEAR)+" , "+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+" "+cal.get(Calendar.AM_PM));
My local timezone is GMT+5:30
Expected result is
Time 13/5/2014, 1:30 0
But I am getting the result
12/5/2014 , 13:30 1
Sorry for you, GregorianCalendar is sometimes the hell. Your problem is following:
If you immediately set the timezone after having set the fields for year, month etc. then this mutable calendar class will only shift the timezone retaining the already set fields containing the local time. Those fields for year, month etc. will NOT be recalculated. This behaviour causes a shift on the global timeline represented by cal.getTime(), too.
In order to force the calendar object to recalculate the fields you need to call a getter. Watch out for following code and especially remove the comment marks to see the effect.
int hour = 17, minute = 0, day = 12, month = 6, year = 2014;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
TimeZone tz1 = TimeZone.getTimeZone("GMT-3");
sdf.setTimeZone(tz1);
Calendar cal = new GregorianCalendar(tz1);
cal.set(year, (month - 1), day, hour, minute);
// System.out.println(sdf.format(cal.getTime()));
// System.out.println("Hour=" + cal.get(Calendar.HOUR_OF_DAY));
TimeZone tz2 = TimeZone.getTimeZone("GMT+0530");
sdf.setTimeZone(tz2);
cal.setTimeZone(tz2);
System.out.println(sdf.format(cal.getTime()));
System.out.println("Hour=" + cal.get(Calendar.HOUR_OF_DAY));
Output with comment-disabled lines:
2014-06-12T17:00+0530
Hour=17
Output with enabled lines after having removed the comment marks:
2014-06-12T17:00-0300
Hour=17
2014-06-13T01:30+0530
Hour=1
My code to calculate remaining days for next birthday gives me following error when I use leap year i.e.; when used with 29th feb
*ERROR**Value 29 for dayOfMonth must be in the range [1,28]
Please help me in this problem...
public int getDaysRemainingForNextBirthDay(){
Calendar cal=Calendar.getInstance();
int currentYear=cal.get(Calendar.YEAR);
int currentMonth=cal.get(Calendar.MONTH);
int birthYear=currentYear;
int birthMonth=Integer.parseInt(m);
int birthDay=Integer.parseInt(d);
if (birthMonth<currentMonth) {
birthYear=birthYear+1;
}
DateTime birthDate=new DateTime(birthYear,birthMonth,birthDay,0, 0);
DateTime currentDate=DateTime.now();
Period datePeriod=new Period(currentDate,birthDate,PeriodType.days());
PeriodFormatter periodFormatter=new PeriodFormatterBuilder()
.appendDays().appendSuffix("").toFormatter();
return Integer.parseInt(periodFormatter.print(datePeriod));
}
The problem is that in Java's Calendar the months are numbered from 0, but in Joda Time they are numbered from 1.
So in your example you pass 2 as the month, which is March according to the Calendar class, but it is interpreted as February by the Joda Time framework.
To solve it just add 1 to the month you get from Calendar when passing it to Joda.
I have seen many examples of working with dates in Android using Calendar and GregorianCalendar classes.
Recently I came across the following in Android Developers Time documentation:
The Time class is a faster replacement for the java.util.Calendar and java.util.GregorianCalendar classes. An instance of the Time class represents a moment in time, specified with second precision.
This prompted me to replace all the Calendar functions with the faster Time class functions.
Here is my code for reading the date stored in the SQLite database:
// extract milliseconds (long) value from SQLite database
Long timeLong = note.getLong(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_DATE));
Time currentTime.set(timeLong);
Here is the partial code for preparing the integer values for populating the date picker and displaying the formatted date string in the mPickDate button:
mDay = currentTime.monthDay; // Day of the month (0-31)
mMonth = currentTime.month; // Month (0-11)
mYear = currentTime.year; // Year
mPickDate.setText(currentTime.format("%A, %d %b %Y")); // using strftime equivalent to dateFormat = new SimpleDateFormat("E, dd MMM yyyy");
Note the format %A used to get the long string for the day of the week.
This part of the formatting code works perfectly well and displays the correct string with the formatted date, including the correct day of the week.
Clicking on the mPickDate button invokes the DatePicker widget, which allows for changing and setting the new date.
The following code shows the handling of the newly selected date from the DatePicker:
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// new method using Time class
currentTime.set(dayOfMonth, monthOfYear, year);
mPickDate.setText(currentTime.format("%A, %d %b %Y"));
// old method using GregorianCalendar class
//mCalendar = new GregorianCalendar(year, monthOfYear, dayOfMonth);
//mPickDate.setText(dateFormat.format(mCalendar.getTime()));
}
};
The mPickDate button gets the correct date string displayed, as selected in the Date Picker, except for the day of the week (%A), which is always shown as Sunday. Why ?
Note that mPickDate.SetText code is identical to the one used earlier to format the button date string, extracted from the SQLite database field.
I had to modify the above code, by adding an extra line of code to set the date value in the currentTime Time object once again:
currentTime.set(dayOfMonth, monthOfYear, year);
currentTime.set(currentTime.toMillis(true));
mPickDate.setText(currentTime.format("%A, %d %b %Y"));
My question is: why it was necessary to use the currentTime.set procedure twice in the above DatePickerDialog.OnDateSetListener code, in order to get the day of the week string to display correctly ?
Would this possibly be an issue with Android Timecode itself (using SDK version 16) ?
I have read all of the docs and there doesnt seem to be too much to really explains the date functions, or the lack there of.
I am trying implement the AlarmManger which needs the time in milliseconds (ms) for the trigger. To test I took the current time and added 5 seconds and that was good.
// get a Calendar object with current time
Calendar cal = Calendar.getInstance();
// add 5 minutes to the calendar object
cal.add(Calendar.SECOND, 5);
If I have a date and time how would I get the ms for that time.
Like "3/2/2011 08:15:00"
How do I turn that into milliseconds?
Use this method.
example:
method call for 3/2/2011 08:15:00
D2MS( 3, 2, 2011, 8, 15, 0);
method
public long D2MS(int month, int day, int year, int hour, int minute, int seconds) {
Calendar c = Calendar.getInstance();
c.set(year, month, day, hour, minute, seconds);
return c.getTimeInMillis();
}
When using AlarmManager you have two choices in setting an alarm - the first is time in ms since device reboot (don't understand that option) or, if you want an 'absolute' time, then you need to provide a UTC time in ms.
I think this should work - I've done something similar in the past...
public long getUtcTimeInMillis(String datetime) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date = sdf.parse(datetime);
// getInstance() provides TZ info which can be used to adjust to UTC
Calendar cal = Calendar.getInstance();
cal.setTime(date);
// Get timezone offset then use it to adjust the return value
int offset = cal.getTimeZone().getOffset(cal.getTimeInMillis());
return cal.getTimeInMillis() + offset;
}
Personally I'd recommend trying to use a non-localised format such as yyyy-MM-dd HH:mm:ss for any date/time string you use if you want to cater for users globally.
The ISO 8601 international standard is yyyy-MM-dd HH:mm:ss.SSSZ but I don't normally go that far.