Convert date into time I am getting wrong value in android - android

I am converting date to time, and I have a problem with minimum date and maximum date.
The minimum date time value is higher than the maximum date time value. I don't know how it is happening. Please help me understand why it is happened.
here i pass the values coming from the date picker when i select the march month 31st date 2014 year.
Date date, minPdate, maxPdate;
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
try {
date = sdf.parse(someDate);
minPdate = sdf.parse("31.02.2014");
maxPdate = sdf.parse("01.03.2014");
lmin = minPdate.getTime();
lmax = maxPdate.getTime();
Log.v("tag","min date "+lmin);
Log.v("tag","max date "+lmax);
} catch (ParseException e) {
e.printStackTrace();
}
Minimum date is March-31-2014 and Maximum date is April-01-2014.
And my result is
min date 1393804800000
max date 1393632000000

You have a wrong date in minDate:
31.02.2014 is invalid date.
try with 28.02.2014.
It seems the long value for 31st feb is treated as 3rd march.
So the long value of 1st march is less than 3rd march.

Java calendar/date APIs are generally considered (by me at least) horrible. As said, 31st feb is being treated as 3rd of march.
However, since you're using Android's DatePicker API, and you seem to want the milliseconds since epoch, you should probably use datePicker.getCalendarView().getDate(). However it might be possible that this is not available and you should just accept the fact that sometimes in java date related APIs month indexing starts with a 0 and sometimes in other classes it starts with 1.
Apparently DatePicker is modeled after Java's Calendar API, which uses 0-based indexing for months. So really you should be using a Calendar object to handle the data.
Calendar cal = new Calendar();
cal.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());
Log.d("tag", "time in millis " + cal.getTimeInMillis());
if you want a Date you can just use cal.getTime()

Related

Difference between 2 dates in days and in double

I am working on an app and i need to get the difference between the actual date and a date inserted by the user, in days and in double.
Any idea on how to make this? I've tried some things but without success.
First you must decide if you want to consider the time of the day and the timezone to calculate the difference, because this can lead to different results.
Example: current date (AKA "today") is April 17th or 18th, depending on where in the world you are. Actually, depending on the time of the day, there might be 3 different "todays" in the world, at the same time. What timezone are you using to calculate the difference?
the user will enter a date: only day, month and year? Will it enter the hours? Are you using the user's device's timezone or some specific zone?
the same questions apply to the current date
Depending on the choices you make, you might get a different result.
Anyway, I'd use this lib: http://www.threeten.org/threetenbp/
or java.time classes, if available in your API level. In both API's you can use the following.
To use a date (day-month-year only) and the device's default timezone, I'd choose the LocalDate class:
// current date in device's default timezone
LocalDate now = LocalDate.now();
// some date from input values (May 10th 2018)
LocalDate dt = LocalDate.of(2018, 5, 10);
// difference in days
long diff = ChronoUnit.DAYS.between(now, dt); // 23
If you want to consider the time of the day (hours, minutes, etc), use a LocalDateTime. But in this case, ChronoUnit.DAYS considers a day has passed when the time is >= the other (ex: the difference between April 17th at 10 AM and April 18th 9:59 AM is zero days, because the time of the day didn't reach 10 AM, so it didn't complete 1 day - with LocalDate this doesn't happen because this class doesn't have time-of-the-day fields and considers only the day, month and year).
If you want to consider everything (date, time, and timezone), including Daylight Saving Time transitions, use a ZonedDateTime instead (the code is very similar, the only difference is that you can choose a timezone to work with):
// current date/time in device's default timezone
ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
// some date from input values (May 10th 2018, 10 AM in New York timezone)
ZonedDateTime dt = ZonedDateTime.of(2018, 5, 10, 10, 0, 0, 0, ZoneId.of("America/New_York"));
// difference in days
long diff = ChronoUnit.DAYS.between(now, dt); // 23
You can choose between the device's default timezone (ZoneId.systemDefault()) or a specific one (ZoneId.of("America/New_York")). You can check all the available timezones with ZoneId.getAvailableZoneIds().
Maybe it doesn't make sense to use current date in one timezone and user's date in another (I'd use the same for both), but that's up to you to decide.
Calendar c = Calendar.getInstance();
Calendar c2 // = what you will get from the user
long diff = c.getTimeInMillis()-c2.
double days = (double) diff/(1000*60*60*24);
that is what i have in mind.
I hope this helps
use this way
public static double getTimeDiffBetweenDate(Date startDateTime, Date finishDateTime) {
long diffInMilliseconds = finishDateTime.getTime() - startDateTime.getTime();
return TimeUnit.MILLISECONDS.toMinutes(diffInMilliseconds) / 60.0;
}

SQLite isn't returning correct records based on a date

I have four buttons on an android app i'm making.
Each button queries an SQLite database and grabs records based on a date. (Buttons are 'Today', 'Week', 'Month', 'All')
The date is stored as a DATETIME in my table, and i'm querying it with a date as well. Everything works well, until i'm grabbing everything that's been done ahead of the previous month.
Example
Todays date is June 29th 2016
I create an entry on June 16th 2016 into my SQLite Database and it stores successfully. I create another entry on June 27th 2016 and it stores successfully.
Now I press the 'Today' button and return 0 records. (Correct)
I press the week button and return 1 record (Correct - Created on June 27th)
I press the month button and return 0 records. (Incorrect. I should be getting 2 records)
The Code
This is the query I use for my database:
String queryString = "SELECT * FROM job_quote_lookup WHERE created_at >= '" + date + "' ORDER BY created_at ASC"
The 'date' is calculated like so:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -31);
Date fromDate = cal.getTime();
date = dateFormat.format(fromDate);
(31 represents the largest possible number of days in a month period)
It seems that the problem occurs when the date goes back a month. If I remove 20 days instead of 31, the date will "June 9th" and i will receive BOTH records as i should. But if the date goes into May, i will receive 0 records.
Other queryStrings i have tried
String queryString = "SELECT * FROM job_quote_lookup WHERE created_at >= date('now','-31 days') ORDER BY created_at ASC"
This didn't seem to work?
I'm still new to Android so apologies if it's a bad question. I have googled around but haven't found anything that might help.
UPDATE: Extra Info
Here is some additional code that might be more helpful
The dateFormat used to time stamp entries into my SQLite is:
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd/MM/yyyy - HH:mm", Locale.getDefault()); //"yyyy-MM-dd HH:mm:ss" - "dd-MM-yyyy HH:mm:ss"
Date date = new Date();
return dateFormat.format(date);
}
The date format used when i'm querying my database is:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
I'm not sure if this is correct, however my reasoning for leaving "HH:mm" off was due to the "Today" option not working correctly as it would return everything greater than the current time (which is obviously nothing in terms of time stamping)
Unable to solve...Ended up converting my database DATETIME to INTEGER and storing the date in milliseconds then just converting between date format and milliseconds to query and display information.
If you want to alter the month of a Java Calendar object you will need to use:
cal.add(Calendar.MONTH, -1);
where the above snippet would roll the month back by one. If you call cal.add(Calendar.DATE, -31) on February 15, for example, you get a weird result because the month won't change but the day will roll over.
Update:
You also have to make sure that the date format you feed into MySQL is correct. MySQL expects the format YYYY-MM-DD for dates, so use this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(cal.getTime());
I recommend using JodaTime if you expect complex calendar operations.

Converting milliseconds to Date object

I am having following code to convert milliseconds to Android Date object.
Date dateObj = new Date(milli);
But problem is that my milliseconds value is having GMT value added in it before i pass it to Date class, add when i print this date object i can see that date object is again adding GMT value in the milliseconds value and because of that my date is displayed as wrong.
So how can i generate Date object with out considering GMT value in it.
For example my milliseconds are 1385569800000 which is getting printed as below:
Wed, 27 Nov 2013 22:00:00 --> +5.30
But the current value of this time stamp without adding GMT is:
Wed, 27 Nov 2013 16:30:00
*UPDAE*
It is not just about printing the date in right format and with right date time.
But i want to use that date object to schedule TimeTask.
So basically i want to create Date object which has proper date time value in it with out adding extra GMT time added in it.
A Date is always in UTC. No need to change that.
When printing the date value, use SimpleDateFormat and call setTimeZone() on it before formatting the output string.
It is not just about printing the date in right format and with right date time.
But i want to use that date object to schedule TimeTask.
TimerTask is just a task and not its scheduling. Timer accepts a Date object for scheduling. The Date is in UTC there as well.
try my code if you a
long currentTime = System.currentTimeMillis();
TimeZone tz = TimeZone.getDefault();
Calendar cal = GregorianCalendar.getInstance(tz);
int offsetInMillis = tz.getOffset(cal.getTimeInMillis());
currentTime -= offsetInMillis;
Date date = new Date(currentTime);
it is work for me
You can try with joda-time API.
Joda-Time provides a quality replacement for the Java date and time classes. The design allows for multiple calendar systems, while still providing a simple API. The 'default' calendar is the ISO8601 standard which is used by XML. The Gregorian, Julian, Buddhist, Coptic, Ethiopic and Islamic systems are also included, and we welcome further additions. Supporting classes include time zone, duration, format and parsing.
http://joda-time.sourceforge.net/key_instant.html
A Date object simply represents a moment in time. Imagine you're on the phone to someone on a different continent, and you say "3...2...1...NOW!". That "NOW" is the same moment for both of you, even though for one person it's 9am and for the other it's 4pm.
You're creating a Date representing the moment 1385569800000 milliseconds after the Java epoch (the beginning of 1970, GMT). That is your "NOW", and it's fixed and unchanging. What it looks like converted into text, however, depends on which timezone you want to display it for. Java defaults to using GMT, which would be right if you were in Britain during the winter, but for (I'm guessing) India you want it in a different time zone. Laalto's answer shows you how to do that.
here is the code,that worked like charm for me:
public static String getDate(long milliSeconds, String dateFormat)
{
// Create a DateFormatter object for displaying date in specified format.
DateFormat formatter = new SimpleDateFormat(dateFormat);
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}

Get time of different Time zones on selection of time from time picker

I have an issue of converting selected hours and minutes to different time zones of countries.
Supposing if i select 10 am in India then i want to know at 10 am in india what will be the time in USA/New york and Tokyo.and Vice versa.
Any help is appreciable...
Thank you
please find the sollution below :
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mma");
TimeZone timezone = TimeZone.getDefault();
TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
Date d = new Date();
sdf.setTimeZone(timezone);
String strtime = sdf.format(d);
Log.e("str time gmt ",strtime);
sdf.setTimeZone(utcTimeZone);
strtime = sdf.format(d);
Log.e("str time utc ",strtime);
i think this will solve your problem
You can probably use Joda Time - Java date and time API. You can get the DateTimeZone depending on the Canonical ID defined in the Joda Time,
DateTimeZone zone = DateTimeZone.forID("Asia/Kolkata");
Joda Time has a complete list of Canonical ID from where you can get TimeZone depending on the Canonical ID.
So, if you want to get the local time in New York at this very moment, you would do the following
// get current moment in default time zone
DateTime dt = new DateTime();
// translate to New York local time
DateTime dtNewYork = dt.withZone(DateTimeZone.forID("America/New_York"));
For getting more idea you can refer Changing TimeZone
Try using Joda-Time library
check the org.joda.time.DateTimeZone class
Here is the API documentation for the same.
you can also get it using , Here no external API is needed
DateFormat format = new SimpleDateFormat("MMMMM d, yyyy, h:mm a");
TimeZone utc = TimeZone.getTimeZone("America/New_York");
System.out.println(utc.getID());
GregorianCalendar gc = new GregorianCalendar(utc);
Date now = gc.getTime();
System.out.println(format.format(now));
you can see more time zone on this Link
Output
America/New_York
December 29, 2012, 11:04 AM
If you don't know city name then you can also use it by Zone name as follow
DateFormat format = new SimpleDateFormat("MMMMM d, yyyy, h:mm a");
TimeZone cst = TimeZone.getTimeZone("US/Eastern");
System.out.println(cst.getID());
GregorianCalendar gc = new GregorianCalendar(cst);
Date now = gc.getTime();
format.setTimeZone(cst);
System.out.println(format.format(now))
Output
US/Eastern
December 29, 2012, 12:38 AM
Not really sure about the solution I'm going to provide but I think you can try it. GMT (Greenwich Mean Time) is a standard. I think you can keep it as a base and calculate the desired time. GMT standard is easily available too.
For example: While installing an OS like Windows XP or Windows 7, we select the time from a drop down menu. My point is, keeping this as the base, you can find the difference between the time zones in NY-US and Tokyo-Japan or vice versa as you desire it.
Hope this helps.

Calendar dayOfMonth off by 1

When trying to get a string for the current date using
DateFormat.getDateInstance().format(calendar.getTime())
it keeps returning the wrong day. For example, it is saying today, July 25th., is July 26th. Also when I use it to sat a date picker, I get the day value by using
dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
When the date picker is set, it also shows the day ahead by 1.
To get the calendar I'm using
Calendar calendar = Calendar.getInstance();
Is there something I'm missing?
Thanks
I would imagine this is because you havent set the timezone to your timezone, and rather than the day being off randomly, the time zone you are in is diferent than GMT (Greenwich Median? Time). Try looking at this example How to handle calendar TimeZones using Java?

Categories

Resources