Maximum digits in Base10 ASCII Representation of UTC Time in android - android

A 4 byte Long integer can give
(2^(32) - 1) = 4294967295
10 digit
Now, the time given by Location Manager in android is currently 13 digit long( like 1366588814000 ).
Can the number of digits increase in future as time progresses ? I don't know in what data type android stores the time.

The return type of the getTime() is long as mentioned in the docs. So you need not worry about the length of the digits. You can always convert that time to a human readable form like
long time = location.getTime();
Date date = new Date(time);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String text = sdf.format(date);
System.out.println(text);

Related

How to Convert "2021-05-14T13:42:48.000Z" string to Date Object?

I am trying to convert "2021-05-14T13:42:48.000Z" string to Date Object.
I have tried this:
DateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DDHH:MM:SS");
And also this, which i saw on stackoverflow only:-
DateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD'T'HH:MM:SS'A'");
But none of it worked.
How can i convert this string to my date object?
Assuming your date string always represents a UTC time (with the 'Z'), you can use format string:
yyyy-MM-dd'T'HH:mm:ss.SSSZ
but you'll first need to replace the Z in your date string with the fixed timezone "+0000", as in "2021-05-14T13:42:48.000+0000".
Try this:
String myDateString = "2021-05-14T13:42:48.000Z"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
Date myDate = dateFormat.parse (myDateString.replace("Z","+0000"));
This will return a date correctly adjusted for your current timezone, in my case 9:42:48am EDT.
There is a more detailed discussion at Converting ISO 8601-compliant String to java.util.Date which you may find useful.
You have used the date-time format incorrectly. It's important to note that the date-time formats have different meanings between capitalized and small letters.
For example: Capital MM means months, whereas small mm means minutes.
To know more about the date formats, you can refer this:
https://cheatography.com/pezmat/cheat-sheets/date-time-formats/pdf/
or this:
https://devhints.io/datetime
And the answer for your case is:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Please do not use SimpleDateFormat or even java.date. All these classes are deprecated.
Instead, rely on the Android available java.time package.
In short:
val source = "2021-05-14T13:42:48.000Z"
val parsed = ZonedDateTime.parse(source)
This will correctly parse the timezone (Z for Zulu/UTC/GMT).
You can verify this, by simply converting the parsed Zoned date time into, for example, Europe/Amsterdam time (which is +2).
val source = "2021-05-14T13:42:48.000Z"
val parsed = ZonedDateTime.parse(source)
parsed.toString() // prints: 2021-05-14T13:42:48Z
parsed.zone // prints: "Z"
ZoneId.of(parsed.zone.id) // returns the ZoneOffset "Z" (correct)
// Convert to Amsterdam Time
val amsterdamDateTime = parsed.withZoneSameInstant(ZoneId.of("Europe/Amsterdam"))
amsterdamDateTime.toString() // prints: 2021-05-14T15:42:48+02:00[Europe/Amsterdam] (2 hours ahead of the Zulu time, also correct).
parsed.format(DateTimeFormatter.ISO_DATE_TIME).toString() // Prints: 2021-05-14T13:42:48Z (correct)
So as you can see, these classes do the right thing (most of the time).
I suggest you use them.

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));

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'.

Getting number of days difference between 2 dates

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();
}

Categories

Resources