Getting number of days difference between 2 dates - android

I am using jxl api to read an excel file in android. When I get a date like "30/11/2012" from excel, the LabelCell output shows me date as "11/30/12".
1) I need to get the output in dd/MM/yyyy format when reading the excel file, because it exists that way in excel, so I wouldn't want to unnecessarily convert it into another format. How to do that ?
2) After reading in the excel column's date, I generate 2 variables, one which has excel date - 20 days (lets call it excelMinus20) and another excel date + 10 days (lets call it excelPlus10.
Now, I would like to check going further, if the current system date (smartphone's date) >= excelMinus20 and current system date <= excelPlus10.
How to do this whole thing using java.text.Date ? I tried using joda time as well, but it's too complicated to use. Please guide me at least in the right direction.
Thanks in advance
Omkar Ghaisas

To parse your date from text format:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse("30/11/2012");
More info : SimpleDateFormat doc
To substract days from your date:
public static Date substractDays(Date date, int days)
{
long millis = date.getTime();
long toSubstract = days * 1000 * 60 * 60 * 60 * 24;
// 1milli 1s 1m 1h 1d
return new Date(millis-toSubstract);
}
Adding some days would be the same, except replace - with +
To get back a String representation from a Date object:
DateFormat formatter = new SimpleDateFormat("...pattern...");
String formatedDate = formatter.format(date.getTime());
EDIT:
You could also do the Date adding/substracting with the method you suggested:
public static Date substractDays(Date date, int days)
{
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, -20 /*or +10*/);
return calendar.getTime();
}
If you want to check if a Date is in an interval, then:
public static boolean isInInterval(Date date, Date from, Date to)
{
return date.getTime()<to.getTime() && date.getTime() > from.getTime();
}

Related

Wrong conversion of time stamp to date android

I'm trying to convert this time stamp value to date but its giving me wrong time. date is correct
TimeStamp : 1423821615
True Value : Fri, 13 Feb 2015 10:00:15 GMT
Android Code shows : Fri, 13 Feb 2015 15:30:15 IST
Here is the code I'm using to convert time stamp to date.
Date dt = new Date((long)timestampInSeconds * 1000);
I tried this code too but same result
public static Date getDateFromTimeStamp(long timestampInMilliseconds) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestampInMilliseconds);
return cal.getTime();
}
Date dt = getDateFromTimeStamp((long)timestampInSeconds * 1000);
I don't know what I'm doing wrong. Please help
Now I explain the whole scenario. My client is from UK and I'm from India (+5:30 ahead). He created appointment for 10 AM in UK obviously. But now I have his database in my local PC. My .NET software it shows same time as it shows in below image of SQL server. But in mobile, it doesn't. PC and mobile both are in same time zone.
I use this code to convert date to time stamp and send this time stamp to mobile app through web service
SELECT DATEDIFF(SECOND,{d '1970-01-01'}, Appointments.DateTime) AS AppointmentTimeStamp FROM Appointments
Here is image of what my .NET software displays
does it matter that record was created when database was in UK time zone. Or I'm still doing a mistake somewhere.
I didn't understand what you wanna get.
If you get time as EPOCH time, you don't have information about time zone where this time stamp was made. So, you should know time zone offset and + or minus this seconds from this time stamp.
But I think the best way to use ISO 8601 format for time stamp, it's easy to convert to any timezone what you need
for example, this code convert ISO data to local time or return current time depends on locale timezone
private long time2LocalTimeZone (String date){
//"2016-07-29T23:07:45.120+00"
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.getDefault());
try {
return sdf.parse(date).getTime();
} catch (ParseException e){
return (new Date()).getTime();
}
}
this code count your offset from GMT timezone and convert to epoch time depends on locale timezone
private long time2LocalTimeZone (long date){
TimeZone tz = TimeZone.getDefault();
Date now = new Date();
int offsetFromUtc = tz.getOffset(now.getTime()) / 1000;
return date + offsetFromUtc;
}

Get the added/modified/taken date of the video from MediaStore

Where do I get the taken date of the video from MediaStore? I got the following fields from MediaStore.
MediaStore.Video.Media.DATE_MODIFIED
MediaStore.Video.Media.DATE_TAKEN
MediaStore.Video.Media.DATE_ADDED
Those fields returned seemly default values -
dateModified: 1477043336
dateTaken: 1477043336000
dateAdded: 1477043352
Formatted dates -
dateModified: 01/01/1970
dateTaken: 01/01/1970
dateAdded: 01/01/1970
I double checked the stock gallery > random video file and I do see the correct dates. I looked at the video columns in MediaStore and I didn't see any other columns which has correct dates.
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
String formattedDate = dateFormat.format(new Date(row.getColumnIndex(MediaStore.Video.Media.DATE_MODIFIED)));
String dateModified = dateFormat.format(new Date(row.getColumnIndex(MediaStore.Video.Media.DATE_MODIFIED)));
String dateTaken = dateFormat.format(new Date(row.getColumnIndex(MediaStore.Video.Media.DATE_TAKEN) * 1000L));
String dateAdded = dateFormat.format(new Date(row.getColumnIndex(MediaStore.Video.Media.DATE_ADDED) * 1000L));
Log.d(TAG, "dateModified: "+dateModified);
Log.d(TAG, "dateTaken: "+dateTaken);
Log.d(TAG, "dateAdded: "+dateAdded);
Log.d(TAG, "dateModified: "+row.getString(row.getColumnIndex(MediaStore.Video.Media.DATE_MODIFIED)));
Log.d(TAG, "dateTaken: "+row.getString(row.getColumnIndex(MediaStore.Video.Media.DATE_TAKEN)));
Log.d(TAG, "dateAdded: "+row.getString(row.getColumnIndex(MediaStore.Video.Media.DATE_ADDED)));
//Just multiply it by 1000 to get correct date
fun convertLongToDate(time: Long): String =
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
DateTimeFormatter.ofPattern("dd MMMM yyyy").format(
Instant.ofEpochMilli(time*1000)
.atZone(ZoneId.systemDefault())
.toLocalDate())
} else {
SimpleDateFormat("dd MMMM yyyy").format(
Date(time * 1000)
)
}
Looking at the annotations on the interface, DATE_ADDED and DATE_MODIFIED are annotated as SECONDS since the epoch, rather than milliseconds. DATE_TAKEN however is annotated as milliseconds since the epoch.
This difference in annotation explains the differences in zeroes that CommonsWare's answer notes. It also guides usage:
Since date formatters usually expect timestamps in millis, you should multiply second values by 1000 first.
Here is a simple function to get actual result of date format.
public String getDate(long val){
val*=1000L;
return new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new java.util.Date(val));
}
Those fields returned seemly default values
I do not know why your second one has three extra zeros at the end. But, using a Unix date converter site:
dateModified = 1477043336 = Fri, 21 Oct 2016 09:48:56 GMT
dateAdded = 1477043352 = Fri, 21 Oct 2016 09:49:12 GMT
And your dateTaken, without the zeros, is the same as dateModified. So, assuming you can figure out where your zeros came from (such as by randomly deciding to multiply the value by 1000L), you have valid timestamps.
Syntax for convert epoch to normal date in android as follows
long date=System.currentTimeMillis(); //current android time in epoch
Converts epoch to "dd/MM/yyyy HH:mm:ss" dateformat
Means 1477043336 = 21/10/2016 09:48:56
String NormalDate = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new java.util.Date(date));

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.

How do I print just the milliseconds (time between last second and next second) of a Date object?

I am building a basic logging utility class and would like to log the date and time down to the millisecond of when the log entry is created. I'm currently using:
Date d = new Date();
String dateToOutput = DateFormat.format( "MM-dd hh:mm:ss", d )
which gives me '05-23 09:05:47'. I would like it to give me the milliseconds of when the log entry is created also and it does not appear that the DateFormat class supports millisecond retrieval.
Like the format "MM-dd hh:mm:ss:zzz" giving '05-23 09:05:47.447'.
Is it possible to do this using the DateFormat class (or a class like DateFormat)? I recognize it is possible to create another date removing the milliseconds part of this date and then subtracting the two and printing the difference but that's just silly. (:
Try this
Date d = new Date();
SimpleDateFormat sdf=new SimpleDateFormat("MM-dd hh:mm:ss SSS");
String dateToOutput = sdf.format(d);
While I think it's silly the DateFormat class doesn't allow easy formatted output of milliseconds, I realized that obtaining the milliseconds from the timestamp is actually quite easy. Every date object is representing a timestamp in milliseconds since 00:00 January 1, 1970 so the timestamp modulo 1000 gives the milliseconds.
I did
Date d = new Date();
String dateToOutput = DateFormat.format( "MM-dd hh:mm:ss", d );
dateToOutput += "." + d.getTime() % 1000;
which, while not ideal, works fine and gives me '05-23 09:05:47.447'.

date retreival in android

In my application i have 2 field, 1 is date and another is recc(is an integer) in database table.
Now i will explain my requirement:
Consider suppose user enters today's date(26-07-2012) and recc as 10.It means that starting from today's date to that +10 date.I got that 10th date from today's date.But what i want is 10th day from today's date means it will surely go to next month also (26-07-2012----5-08-2012),but i have to know the count of date which falls in this particular month,(i.e)between 26-07-2012----5-08-2012 how many days it will fall within this month.I think i have explained my problem clearly,if not i am ready to give more explanation.Thanks in advance.
Date value:
EditText date=(EditText)findViewById(R.id.startdateexp);
String startdate=date.getText().toString();
you can do this by following way:
1. Get date from Database.
Now get day of month from the date by following method:
DateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = iso8601Format.parse(dateTime);
} catch (ParseException e) {
Log.e(TAG, "Parsing ISO8601 datetime failed", e);
}
Calendar cal=Calendar.getInstance();
cal.setTime(date);
int currentDay= cal.get(Calendar.DAY_OF_MONTH);
calculate Last day of month by:
int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
If you're using the Date class you can offset it by the number of days converted to milliseconds to create a new Date:
Date datePlusRecc = new Date(oldDate.getTime() + recc*86400000); // 86400000 = 24*60*60*1000
Note that this is useable only when recc is relatively small (< about 20), because otherwise the multiplication will overflow.
Just use the java.util.Date class combined with your date in milliseconds.
In a for loop add one day to the one version in milliseconds and convert it back to Date. Get the Month out of the Date Object and compare it with the current month. As soon as the month is a new one you have your total count of days in the current month.
Date currentDate = new Date(currentMillis);
long countingMillis = currentMillis;
int daysInSameMonth = 0;
while(true){
daysInSameMonth++; // if the actual date schould not count move this line at the button of the while
countingMillis += 1000*60*60*24;
Date dt = new Date(countingMillis);
if(currentDate.getMonth() != dt.getMonth())
break;
}

Categories

Resources