I'm working on Android application, and I want to convert user-selected local time (device time) into UTC seconds. After that, I have to convert it again and display in the device's time zone. Can anyone suggest how to do this in Kotlin?
I want to convert user-selected local time (device time) into UTC seconds
You're thinking about this incorrectly. Timestamps, including device time, do not have a time zone. All timestamps are seconds since Jan 1 1970 00:00 UTC, regardless of device time zone. If the user selects a time, and you have that time as a timestamp, it's already in the right format. You can think of it as "UTC seconds," since it's based on a time in UTC, but there's no such thing as timestamps that aren't in such "UTC seconds."
The only time you need a time zone is for converting to a date, displaying it to a user, etc.
Constructs a SimpleDateFormat using the given pattern and the default date format symbols for the default FORMAT locale
fun localToGMT(): Date? {
val date = Date()
val sdf = getDateInstance()
sdf.timeZone = TimeZone.getTimeZone("UTC")
return DateFormat.getDateInstance().parse(sdf.format(date))
}
fun gmttoLocalDate(date: Date):Date? {
val timeZone = Calendar.getInstance().getTimeZone().getID();
val local = Date(date.getTime() + TimeZone.getTimeZone(timeZone).getOffset(date.getTime()));
return local
}
Related
so, let's say I want to save a data in my database and save the timestamp (date and time) for the time the data saved in database. for example in +3:00 GMT.
now the timezone changed and the saved time when I getting it is changing too but I don't want that.
I want it to show the time in that timezone not current
and I using currentTimeMillis() for getting time
it's my code of getting time
val timeStamp = System.currentTimeMillis()
and code for getting from database in my view holder
val tsLong = currentItem.timeStamp
System.currentTimeMillis will always report in UTC regardless of the user's timezone.
I would recommend using Instant to store all your timestamps. Instants can easily be converted to any timezone. Instant has the following advantages:
Explicitly always in UTC/GMT timezone
toString() to ISO date format that is much more readable than milliseconds from the epoch
Far too often when we use milliseconds from the epoch we can't easily read them and it's ambitious if the field is seconds from the epoch or milliseconds. using Instant removes this ambiguity and makes things easier for developers.
In timestamp variable, I want to get the timestampt value with the current hour, minute and second. The currentDataTime gives me the time in this format: 2020-08-28 17:18:02.
Currently, the timestamp variable returns me 1598645882634 (the last 3 numbers are the miliseconds) but when I convert it in a online conversor to a Human readable format, it gives me 08/28/2020 # 8:18pm (UTC). The only one problem is the hour and minute tha is 3 hours different because of my zone. How can I convert the date AND time to timestamp?
object DateTime {
val currentDataTime: String
#SuppressLint("SimpleDateFormat")
get() {
val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
return dateFormat.format(Date())
}
val timestamp: String
get(){
val formatter: DateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val date = formatter.parse(currentDataTime) as Date
return date.time.toString().dropLast(3) //it is returning
}
}
A Unix timestamp is defined to be (almost) UTC. It carries no timezone information so it cannot be shifted according to a timezone difference without everything based on it falling apart. (If you'd like to hardwire it anyway, according to your example just add your timezone difference in milliseconds. But read on first.)
Localized time can only be interpreted consistently as long as the proper timezone is attached. It jumps back and forth whenever daylight-savings time starts or ends. If that's not complicated enough, the rules for daylight-savings time may change at any time (and do so around the globe).
Your online converter apparently just took a UTC-based timestamp and displayed it according to your local timezone.
To handle localized date and time values, use the multiplatform date/time library kotlinx-datetime. In the README section Converting an instant to local date and time components you'll find this example:
val currentMoment: Instant = Clock.System.now()
val datetimeInUtc: LocalDateTime = currentMoment.toLocalDateTime(TimeZone.UTC)
val datetimeInSystemZone: LocalDateTime = currentMoment.toLocalDateTime(TimeZone.currentSystemDefault())
There you'll also find elaborate explanations on which type of date and time to use in which scenario.
I am trying to set the date time of a local object. Here is my code:
val date = DateTime() //returns UTC time
val dateTimeZone = DateTimeZone.getDefault() //returns UTC
val localDateTime = LocalDateTime() //returns UTC
My phone settings are set to automatic date time, and my current time zone is Mountain Time.
How can I get the current time in my time zone (the one appearing on my phone)?
If DateTimeZone.getDefault() returns "UTC", that's because the device's default timezone is set to it, so all classes will refer to it unless you specify another zone.
To get the date and time at a specific timezone, you can do:
val date = DateTime(DateTimeZone.forID("America/Denver"))
val localDateTime = LocalDateTime(DateTimeZone.forID("America/Denver"))
Note that America/Denver is just one of the many regions that uses Mountain Time. That's because Joda-Time uses IANA zones names (in the format region/city), so you must choose the best one accordingly from this list: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
Optionally, you can also change the default timezone:
DateTimeZone.setDefault(DateTimeZone.forID("America/Denver"))
With this, just calling LocalDateTime() or DateTime() will use America/Denver as the default zone.
But remind that this will change the default timezone for the whole JVM, so think if that's what you need before doing so.
I tried:
TimeZone.getDefault();
I tried:
Calendar mCalendar = new GregorianCalendar();
TimeZone mTimeZone = mCalendar.getTimeZone();
I tried:
Calendar c = Calendar.getInstance();
mTimeZone = c.getTimeZone();
No matter what I try... it gives me a default of 0 and GMT. My app just cannot seem to get the time zone (it should read -4 or ET, i.e. eastern USA time zones)
The strange thing is... my clock displays the correct time on my phone.
the "use automatic time zone" is checked in settings of my android device.
So why can't I get the local time in my app? how does the Android clock able to achieve this but not me?
I have checked online and cant seem to find anything. Is there at least a way to sync with the clock app and receive it's time to display on my app as well? Is there ANY way to get the correct time on my app?
System.getMilliseconds() return the time since epoch, which would only function as the current time in areas that use GMT. (As long as what you are using doesn't make it's own conversion)
To get local time in milliseconds since epoch, you can use this function:
// Kotlin
fun getLocalTime(): Long
{
val currentDate = Calendar.getInstance()
return currentDate.timeInMillis + TimeZone.getDefault().getOffset(currentDate.timeInMillis)
}
Which in Java would probably look like this:
// Java
static long getLocalTime()
{
Calendar currentDate = Calendar.getInstance();
return currentDate.getTimeInMillis() + TimeZone.getDefault().getOffset(currentDate.getTimeInMillis());
}
The function takes the time since epoch and adds to it the timezone offset of the phone's local timezone.
I have tow issues :
1- get UTC time from Android device
2- Convert it to UNIX time format ( millseconds )
I appreciated any feedback can help
I believe this should work:
Date now = Calendar.getInstance().getTime(); // this gets you current time as a Date
long milis = now.getTime(); // this gets you current time in UNIX format