Joda DateTime object adding +1 hour - android

i have the following code:
Log.e(TAG, "startTime = " + startTime);
DateTime dateTimeStart = new DateTime(startTime);
Log.e(TAG, "dateTimeStart = " + dateTimeStart );
.
which when logged out produces the following:
startTime = 2014-10-30T12:00:00+00:00
dateTimeStart = 2014-10-30T13:00:00.000+01:00
.
Why is an extra hour getting added on to the original time?
edit
How can i remove the +1:00, i haven't specified that.
Thanks

DateTime is an object consisting of a date, a time, and a timezone. In your case, you took startTime and converted it into an equivalent DateTime using the default system timezone.
+01:00 means "this timestamp is in some UTC+1 timezone", so 12:00:00.000+00:00 means the same as 13:00:00.000+01:00
So your timestamp was created at 12:00 British time = 13:00 Central European time.
If you want the time in UTC, do
DateTime dateTimeStart = new DateTime(startTime, DateTimeZone.UTC);

Use split method.
String splitDateTime[]=dateTimeStart.split("\\+");
dateTimeStart=splitDateTime[0];

Default DateTime::toString() method returns date in format yyyy-MM-ddTHH:mm:ss.SSSZZ .
+01:00 and +00:00 are the timezone offsets (ZZ in date format).
So if you want to print date without timezone offset, you should use another format. E.g. with method DateTime::toString(String):
String dtFormat = "yyyy-MM-dd'T'HH:mm:ss";
Log.e(TAG, "startTime = " + startTime.toString(dtFormat));
...
Log.e(TAG, "dateTimeStart = " + dateTimeStart.toString(dtFormat ));

Related

Same Milliseconds values coming for different dates

I store my values in database by converting the date value in milliseconds,so to get the latest date on top by using order by desc query. The order is coming as required but if i enter date 02/01/2016 and 01/30/2016 both are storing same milliseconds value.
String date = "02/01/2016";
String month = date.substring(0, 2);
String day = date.substring(3, 5);
String year = date.substring(6, 10);
Calendar c1 = Calendar.getInstance();
c1.set(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day));
long left = c1.getTimeInMillis();
After debugging i got the following milliseconds values
02/01/2016----61414914600000
and 01/30/2016----61414914600000
Anybody knows why this happening?
Using SimpleDateFormat value I am getting different milliseconds value:
Date date;
String dtStart = "02/01/2016";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
try {
date = format.parse(dtStart);
long timeMills=date.getTime();
System.out.println("Date ->" + date);
} catch (Exception e) {
e.printStackTrace();
}
I ran your initial code and it functions almost as expected. A few points:
You mention millisecond 61414914600000. That's not correct because it's 1900 years into the future:
http://currentmillis.com/?61414914600000
I'm pretty sure you got that number from a Date object, not from a Calendar: http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#Date(int, int, int)
As Mat said the month is zero-based for Calendar and the line where you call the setter should subtract 1:
c1.set(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day));
You answered your own question with another snippet of code but Date is deprecated, Calendar should be used instead. Your original code in the initial post was essentially correct (except the zero-based month). You should make sure that you know where your output is coming from and / or that you don't forget to build the code before running it.

Android:Display time after adding GMT time zone

I am working on a App in which i want to display notification time.
I can display notification time but not able to add time zone in it.
My current location is Pakistan and i want to add GMT+5:00
My code is attached
String currentDateTimeString = DateFormat.getTimeInstance().format(notif.At);
textViewTime.setText(currentDateTimeString);
in this code, notif.At is dateTime variable. I also attached screenshot of my app, i want to ask you , how to add timeZone value in notif.At. Thanks!
Update
You mark time with timezone in order to solve internationalization problem, I understand, right?
If so, I think it could be better to convert your date to UTC date. When you change to another timezone, just convert this UTC Date to local.
public static Date localToUtc(Date localDate) {
return new Date(localDate.getTime()-TimeZone.getDefault().getOffset(localDate.getTime()));
}
public static Date utcToLocal(Date utcDate) {
return new Date(utcDate.getTime()+TimeZone.getDefault().getOffset(utcDate.getTime()));
}
Old answer
If your notif.At is Dateobject, it's a same question actually:
TimeZone tz = TimeZone.getDefault();
Date date = new Date();
final String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
String result = sdf.format(date);
Log.d("Date ", "date: " + result + " " + tz.getDisplayName(false, TimeZone.SHORT));
print:
date: 2015-03-31 18:45:28 GMT+08:00
You can try java.time api;
Instant date = Instant.ofEpochMilli(1549362600000l);
LocalDateTime utc = LocalDateTime.ofInstant(date, ZoneOffset.UTC);
LocalDateTime pst = LocalDateTime.ofInstant(date, ZoneOffset.of("+05:00"));
LocalDateTime is = LocalDateTime.ofInstant(date, ZoneOffset.of("+05:30"));

DateTime incorrect month and how convert to dd/mm/yyyy in database

I want to let the user choose a Date from a DatePicker and store it into database, and then convert it to dd/mm/yyyy format.
dp =(DatePicker)findViewById(R.id.DateActivity);
setDate.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
requestDate.setText("Day" + dp.getDayOfMonth() + " Month " + (dp.getMonth() + 1)+ " Year " + dp.getYear());
}
});
The output is Day 9 Month 2 Year 2014.
The output months is less by one for every month I choose so I add 1 to the month. Why this is the case?
But the main problem is how do I convert it to 09022014 and store it in the database? If the db has the format dd/mm/yyyy does it means it will not accept my output?
java.util.Calendar treats the months as a zero-based list, so the DatePicker follows this convention as well (see the documentation for DatePicker.init). It's confusing, but that's just the way Java does it (for now, at least). Adding 1 like you're doing will work just fine.
As for converting the date, you can use the SimpleDateFormat class to format the date however you like. For what you said, the format pattern string would be "ddMMyyyy". See the sample code below:
// Build Calendar object from DatePicker fields.
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, myDatePicker.getMonth());
cal.set(Calendar.DAY_OF_MONTH, myDatePicker.getDayOfMonth());
cal.set(Calendar.YEAR, myDatePicker.getYear());
// Convert date to desired format.
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
String dateString = sdf.format(cal.getTime());
int dateInt = Integer.parseInt(dateString); // if you want it as an int instead
You may want to consider storing the date as 20140209 ("yyyyMMdd", year-month-day) instead for sorting purposes, as that will naturally allow it to be sorted chronologically.
For your second problem (putting it into the database) you can simply create a string like this:
String todb = dp.getDayOfMonth() + "/" + (dp.getMonth() + 1)+ "/" + dp.getYear();
Which will return a string like 09/21/2014.
Now, as for your first problem (the month being off by one), I believe this stems from a CalendarView.OnDateChangeListener. It says:
month The month that was set [0-11].
I would bet that this was also implemented on DatePicker's (or you're using the CalendarView with the DatePicker), so January is 0 and December is 11. So your way of changing the month by 1 is a perfectly fine way to do it.

How to fetch current GMT value?

In my app, I am using GeoNamesAPI for fetching the current time at any location.
I have registered for using that.
My code looks like:
Timezone currentTimeZone;
org.geonames.WebService.setUserName("mathew");
currentTimeZone = GeoNamesAPI.fetchTimeZone(latitude, longitude);
The problem is when I check time at any ocean, this currentTimeZone returns null.
So in that case, I show the GMT value.
String time = null;
Integer timeZone = (int) (((longitude / 7.5) + 1) / 2);
if (timeZone >= 0) {
time = "GMT+" + timeZone;
} else {
time = "GMT" + timeZone;
}
So the time value will be of the kind GMT+somevalue. I want to find another solution for this case. In this case also I want to display the time value. How can I do that? Is there any way to get the GMT value? Note: I dont want to show the date only time is required.
Thanks in advance.
I got it worked. Code is given below:
Integer timeZone = (int) (((longitude / 7.5) + 1) / 2);
DateFormat dateformat = DateFormat.getTimeInstance(DateFormat.SHORT);
dateformat.setTimeZone(TimeZone.getTimeZone("gmt"));
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, timeZone); //Adding/Subtracting hour to current date time
String newdate = dateformat.format(cal.getTime());

Comparing the Date in Android

I am using SQLITE database and I store the date as a String. Now I want to compare both the string as a date. While I am using
String sqlQuery = "SELECT title,edate FROM lookup WHERE" + ((Date)df.parse("?")).getTime() + "<=" + date1.getTime();
c= db.rawQuery(sqlQuery,new String[]{"edate"});
it is giving error at run time. Please Tell me how can I compare two String as a Date.
Thank You
Deepak
You want numbers in order to compare easily. I recommend POSIX (or unix) time, which counts seconds since a fixed point in about 1970.
Use an SQLite strftime function to convert your string to POSIX epoch time (check out the %s option) http://sqlite.org/lang_datefunc.html
Then use the Java functions to get epoch time: http://download.oracle.com/javase/6/docs/api/java/util/Date.html#getTime()
"SELECT title, edate FROM lookup WHERE strftime(edate,'%s') < " + (Date1.getTime()/1000)
String formatString = "dd-MM-yyyy"; // for example
SimpleDateFormat df = new SimpleDateFormat(formatString);
Date date1 = df.parse(string1);
Date date2 = df.parse(string2);
if (date1.before(date2)) {
System.out.println("first date is earlier");
}

Categories

Resources