1

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?

Τζιότι
  • 151
  • 2
  • 11
  • 1
    Does this answer your question? [How to convert date string to timestamp in Kotlin?](https://stackoverflow.com/questions/48838992/how-to-convert-date-string-to-timestamp-in-kotlin) – kelvin Feb 08 '21 at 06:13
  • 1
    @kelvin No, this is not the right ans – Τζιότι Feb 08 '21 at 06:16
  • 1
    @Τζιότι You can try this [library](https://github.com/JakeWharton/ThreeTenABP) – Kaushik Feb 08 '21 at 06:49

2 Answers2

1

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.

Ryan M
  • 18,333
  • 31
  • 67
  • 74
0

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
}
Morpheus
  • 550
  • 1
  • 9
  • 23