Parse.com date saving incorrectly - android

I'm using Parse as a data store for an app I'm building. I have a Date parameter within the class that stores the expiry date of a food that is saved to Parse. The date is inputted using a datepicker (code below)
The date picker is created as such:
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
expiry_date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DatePickerDialog(AddItem.this, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
And the update label method converts it to a readable date and displayed in an EditText
private void updateLabel() {
String myFormat = "dd/MM/yyyy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.UK);
EditText update = (EditText) findViewById(R.id.expiry_date);
update.setText(sdf.format(myCalendar.getTime()));
}
Then, when the date is saved, it converts in from a string to a date
String dateString = expiry_date.getText().toString();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(dateString);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
This displays the correct date, as I'd expect. When saved however, the date is incorrect. For example, if I chose 28/08/2015, it would be saved in the Parse core as 27/08/2015:2300. It always saves as the day before with 11pm appended to it.
I wouldn't mind a time being appended to the date, but I'd prefer it to be 11:59pm on the day I picked, so I can compare dates later.
When the dates are displayed, they actually display the correct date (as in, the one picked from the date picker), rather than the saved date in Parse.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String date = sdf.format(Calendar.getInstance().getTime());
Date datecomp = new Date();
datecomp.getDate();
int check = object.getDate("expiry").compareTo(datecomp);
Format formatter = new SimpleDateFormat("dd/MM/yyyy");
I'm assuming this is something to do with the date conversion, but I can't figure out why it's doing this, and I've looked at a lot of different sources, but none seem to describe my problem. Any help would be much appreciated

Parse stores dates as GMT reference (not +3h or -2h GMT e.i someone from Turkey and someone from US have different time at the same moment.) So you should make localization on your application via keeping client timezone in parse db.
int offsetInMs = 3600000;
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
TimeZone timeZone = calendar.getTimeZone();
TimeZone gmt0 = timeZone.getTimeZone("GMT0");
TimeZone gmtNewYork = timeZone.getTimeZone("America/New_York");
TimeZone gmtLondon = timeZone.getTimeZone("Europe/London");
TimeZone gmtIstanbul = timeZone.getTimeZone("Asia/Istanbul");
TimeZone local = timeZone.getDefault();
System.out.println(gmt0.getID()+" -> "+gmt0.getOffset(date.getTime())/offsetInMs);
System.out.println(gmtNewYork.getID() + " -> " + gmtNewYork.getOffset(date.getTime())/offsetInMs);
System.out.println(gmtLondon.getID() + " -> " + gmtLondon.getOffset(date.getTime())/offsetInMs);
System.out.println(gmtIstanbul.getID() + " -> " + gmtIstanbul.getOffset(date.getTime())/offsetInMs);
System.out.println(local.getID()+ " -> " + local.getOffset(date.getTime())/offsetInMs);
i.e. Your local time zone is GMT+2 and local time is 15:00,
Parse save it as 13:00(GMT). You shoud create a column named GMTOffset which keeps GMT+2.
Results:
GMT0 -> 0, America/New_York -> -4, Europe/London -> 1, Asia/Istanbul -> 3, Asia/Istanbul -> 3
I think that Parse basetime is GMT0. Create a column named GMTOffset which keeps -4, 1, 3, 3 (user local offset).
Additionally, if you will use parse time in your application, Parse may localize time on the client side. Please check that also.
P.S. as my experience, client side time is not reliable, you should use your server(if exist) time.

Related

How to save a Date from DatePicker into SQLite with Android Studio

I have a SQLite DB for my Android app project and I would like to save a date from a Date Picker.
TO be as efficient as possible, I cannot insert that date as a String.
So I'm trying to save my date as an Integer or a Long but I check all around the web and nothing clear enough to help me...
Here is my code:
public DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the chosen date
TextView dateView = (TextView) findViewById(R.id.newdatepicked);
// Create a Date variable/object with user chosen date
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0);
cal.set(year, month, day, 0, 0, 0);
Date date = cal.getTime(); // CAN I USE THIS LINE?
// Format the date using style MEDIUM and FR locale
DateFormat df_date = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);
String dateDF= df_date.format(dateDF);
// Display the formatted date
dateView.setText(dateDF);
}
};
And my code to insert all my data:
public void SaveAlert(View v) {
String Article = tvArticle.getText().toString();
long DateEntree = calendar.getTimeInMillis(); // This line is working very well
long DateSortie = ;///////// I CANNOT FIND OUT HOW TO HANDLE THIS ...
My issue is with DateSortie.
Please let me apologize for my English and thanks a lot for your help
you can still store it as string and then retrieve them using the format you want for example
Calendar calendar = Calendar.getInstance();
/* to display time*/
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm");
/* to display date in the given format */
DateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
/*get the date using */
Date dDate = dateFormatter.parse(yourObject.getTaskDate());
/*set the date */
calendar.setTime(dDate);

How to get user's timezone and convert time saved in database according to the user's timezone? Please see details

I'm developing an app in which I'm saving the time when the post was posted.
I'm getting that time by using this code:
DateFormat currentTime = new SimpleDateFormat("h:mm a");
final String time = currentTime.format(Calendar.getInstance().getTime());
Now, what I want is I want to get user's timezone and convert the time saved in database using his/her timezone to his/her local time.
I tried doing this using code:
public String convertTime(Date d) {
//You are getting server date as argument, parse your server response and then pass date to this method
SimpleDateFormat sdfAmerica = new SimpleDateFormat("h:mm a");
String actualTime = sdfAmerica.format(d);
//Changed timezone
TimeZone tzInAmerica = TimeZone.getDefault();
sdfAmerica.setTimeZone(tzInAmerica);
convertedTime = sdfAmerica.format(d);
Toast.makeText(getBaseContext(), "actual : " + actualTime + " converted " + convertedTime, Toast.LENGTH_LONG).show();
return convertedTime;
}
but this is not changing the time.
This is how I'm trying to convert time saved in database using above method (postedAtTime is the time which is getting retrieved from database):
String timeStr = postedAtTime;
SimpleDateFormat df = new SimpleDateFormat("h:mm a");
Date date = null;
try {
date = df.parse(timeStr);
} catch (ParseException e) {
e.printStackTrace();
}
convertTime(date);
Please let me know what's wrong in my code or if this is wrong way?
The time string you're storing is not sufficient to be able to change timezones after the fact (h:mm a is only hours, minutes and am/pm marker). In order to do something like this you need to either store the timezone the original timestamp was in or better yet store the time in a deterministic manner like always UTC.
Example code:
final Date now = new Date();
final String format = "yyyy-MM-dd HH:mm:ss";
final SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
// Convert to UTC for persistence
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
// Persist string to DB - UTC timezone
final String persisted = sdf.format(now);
System.out.println(String.format(Locale.US, "Date is: %s", persisted));
// Parse string from DB - UTC timezone
final Date parsed = sdf.parse(persisted);
// Now convert to whatever timezone for display purposes
final SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm a Z", Locale.US);
displayFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
final String display = displayFormat.format(parsed);
System.out.println(String.format(Locale.US, "Date is: %s", display));
Output
Date is: 2016-06-24 17:49:43
Date is: 13:49 PM -0400

Format date like system format using Time.getCurrentTimezone()

I'm using Time.getCurrentTimezone()to get the current timezone and therefore the date.
I'm getting and formatting it like this:
private void setDate() {
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
tvdate2.setText(today.monthDay + "-" + today.month + "-" + today.year);
}
How can I format the date according to the system settings?
I didn't manage to get it done via SimpleDateFormat...
You could get time in any format by using SimpleDateFormat class. Please refer to this
Calendar cal = Calendar.getInstance();
String currentDate = cal.get(Calendar.DAY_OF_MONTH)+"/"+(cal.get(Calendar.MONTH)+1)+"/"+cal.get(Calendar.YEAR);
Date date = new SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.ENGLISH).parse(currentDate);

Android Timezone Ids are not matching with System Timezone Ids issue

I am working on timezones concept in Android.
I want to change the timezone of the Android tablet by taking the timezone from the App Variable in the application. I am getting the System TimeZones as the variable value i.e like
Dateline Standard Time
UTC-11
Samoa Standard Time
Hawaiian Standard Time
Alaskan Standard Time
Pacific Standard Time (Mexico)
Pacific Standard Time
US Mountain Standard Time
Mountain Standard Time (Mexico)
Mountain Standard Time
Central America Standard Time
Central Standard Time
Central Standard Time (Mexico)
Canada Central Standard Time
SA Pacific Standard Time
From Android case, I am getting Timezone Id's like
Africa/Harare
Africa/Johannesburg
Africa/Kigali
Africa/Lubumbashi
Africa/Lusaka
Africa/Maputo
Africa/Maseru
Africa/Mbabane
Africa/Tripoli
Asia/Amman
Asia/Beirut
Asia/Istanbul
Asia/Jerusalem
Asia/Nicosia
Asia/Tel_Aviv
CAT
EET
Egypt
Etc/GMT-2
Europe/Chisinau
Europe/Helsinki
and my code is
if (mCalendar != null) {
mCalendar = Calendar.getInstance();
}
else
{
String[] allTimeZones = TimeZone.getAvailableIDs();
Arrays.sort(allTimeZones);
for (int i = 0; i < allTimeZones.length; i++) {
System.out.println(allTimeZones[i]);
}
TimeZone tz = TimeZone.getTimeZone(String.valueOf(Jordan Standard Time));
mCalendar = Calendar.getInstance(tz);
String name = tz.getID();
System.out.println("TimeZone "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " + name);
}
As 'Jordan Standard Time' is variable from application is not like Timezone of tablet available Id's, Timezone is not changing.
If I replace the Timezone with 'Africa/Tripoli' manually, the timezone is replacing with this one.
My issue now is I would like to convert the system timezones to Tablet Timezone Ids and display it in Android Application.
plz use this function that is display GMT Time display if you change timezone from you android phone.
public static String GetDateForGMTDate(String dateString) {
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-mm-dd");
SimpleDateFormat formatter1 = new SimpleDateFormat(
"yyyy-mm-dd");
Date date = null;
try {
date = formatter.parse(dateString);
System.out.println(date);
System.out.println(formatter.format(date));
Calendar cal = Calendar.getInstance();
cal.setTime(date);
Log.i("Time zone", "gettime=" + cal.getTime());
cal.add(Calendar.MINUTE, (-1 * getTimeZoneDifference()));
Log.i("Time zone", "after gmt +gettime=" + cal.getTime());
date = cal.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return formatter1.format(date);
}
public static final int getTimeZoneDifference() {
long currentTime = System.currentTimeMillis();
int gmtcurrentOffset = TimeZone.getDefault().getOffset(currentTime);
int gmtOffset = TimeZone.getTimeZone("GMT").getOffset(currentTime);
int minuteDifference = (((gmtOffset - gmtcurrentOffset) / 1000) / 60);
return minuteDifference;
}
use 1st function and pass any date with yyy-mm-dd formate as a string. and that function will return gmt formate real date-time.
i already use it.
its working fine.i hope its useful to you.

Cant fetch current time, date showing year as 1970

public static final String inputFormat = "HH:mm";
private Date date;
private Date dateCompareOne;
private Date dateCompareTwo;
LINE 5:
private String compareStringOne = String.valueOf(SetTimeActivity.intFromTimeH)+ ":"+ String.valueOf(SetTimeActivity.intFromTimeM) ;
LINE 6:
private String compareStringTwo = String.valueOf(SetTimeActivity.intToTimeH) + ":"+ String.valueOf(SetTimeActivity.intToTimeM);
SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);
private void compareDates()
{
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
date = parseDate(hour + ":" + minute);
dateCompareOne = parseDate(compareStringOne);
dateCompareTwo = parseDate(compareStringTwo);
if (!(dateCompareOne.before( date ) && dateCompareTwo.after(date))) {
....
I am trying to check if current time falls between the specified time. For that I am converting the specified time into strings first (in Line5 & Line6). Even though I get the integer values correct, the string formed always shows "0:0".
Also, the year is shown as 1970 (The date & the day shown are wrong as well).
I need to get the current time. What am I doing wrong?
private Date parseDate(String date) {
try {
return inputParser.parse(date);
} catch (java.text.ParseException e) {
return new Date(0);
}
}
The parseDate() function returns the time elapsed since the 1st of January 1970. This is known as the Unix Epoch, and it's how all time is represented in Unix computers. By running the parseDate function on a string containing just hours and minutes, you're creating a Date object which represents a time HH:mm past the first of January 1970.
Your code is using a really odd way of getting the current time. Converting a Calendar to two ints, then to a string and finally parsing back to a Date is going to be inefficient and open you up to all sorts of needless errors.
When you initialise a new Date object it is automatically assigned the time of initialisation. Therefore:
Date d = new Date();
would result in d being the moment of initialisation (that is, this year, month, day, hour, minute, second and microsecond). Then you can just use Date.after() and Date.before().
If you still want to do it via the Calendar method, then you'd be better served by:
cal = Calendar.getInstance();
Date d = cal.getTime();
It may be that you've got other issues, but it's worth doing it properly first. When you pass data by writing it as a string (especially when it's time related, with all sorts of ambiguities about what "12" actually represents) you lose all the advantages that language typing gives you.
this code help you
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE); if (c.get(Calendar.AM_PM) == Calendar.AM)
am_pm = "AM";
else if (c.get(Calendar.AM_PM) == Calendar.PM)
am_pm = "PM";
// Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
String formattedDate = df.format(c.getTime());
Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();
If you already work with Date objects why not using the Date.after(...) and Date.before(...) methods.

Categories

Resources