Converting Time to another timezone - android

I have a simple code where i want to convert a certain given time to another time zone , in my case the time is local to UK , but i need to convert the time to another timezone if the user lives in different country , i have tried this simple code but it is not working for me , it is giving me random hour 04:00
any help would be appreciated guys
This is the code
var localTime = "16:00" // simulating time to Uk timezone
localtime.text = localTime
timeZone.setOnClickListener {
val localTimes = "16:00"
val timeFormatter = SimpleDateFormat("hh:mm", Locale.UK)
val timezone = TimeZone.getDefault() // get device timezone
timeFormatter.timeZone = timezone
val timeToFormat = timeFormatter.parse(localTimes)
val formattedTime = timeFormatter.format(timeToFormat)
localtime.text = formattedTime
}

Related

If condition between two date by hour

I'm makeing an app that want some text color Change when current time between 2 date.
like I have schedule with tasks, and from 1:00PM to 5:00PM there is a task I have to do.
Want to make a condition if current time between two date change the color of this text.
it's not just about color.
it's a lot of things put it's depend on this condition
Puted the two date in one TextView
val simpleDateFormat = SimpleDateFormat("h:mm a")
val time = simpleDateFormat.format(item.startDate) + "-" + simpleDateFormat.format(item.endDate)
looks like your item.startDate and item.endDate are Date instances. so you need also a Date with current time, which you can get with
val currDate = Calendar.getInstance().getTime()
or even by creating new Date instance (is set to current by default)
val currDate = Date()
now you can convert Date to long timestamp
val startDateAsTimestamp = item.startDate.getTime()
val endDateAsTimestamp = item.endDate.getTime()
val currDateAsTimestamp = currDate.getTime()
and now your if would be
if (currDateAsTimestamp >= startDateAsTimestamp &&
currDateAsTimestamp <= endDateAsTimestamp) {

Getting Date with Start time of the Day

I am using below function to take the today's date :
fun getCurrentDateTime(dateFormat: String): String {
val Datetime: String
val c = Calendar.getInstance()
val dateformat = SimpleDateFormat(dateFormat, Locale.getDefault())
Datetime = dateformat.format(c.time)
return Datetime
}
I have filter for today to sort fetch today's filtered data. But, With the above function I am filtering with the same values,
Means start date for Today and end date for Today are both same.
I want it different.
Means :
Start Date should be 1639560609 (Wednesday, 15 December 2021 00:00:00 GMT+05:30)
and
End Date should be Current time (which I am getting with above function)
So, The Issue you got that I want the Today's start Date with start time of the day.
How ? Thanks.
Use LocalDateTime to get current date and start of the day
val dateFormatter = DateTimeFormatter.ofPattern("EEEE, d MMMM yyyy HH:mm:ss")
val localDate = LocalDate.now() // your current date time
val startOfDay: LocalDateTime = localDate.atStartOfDay() // date time at start of the date
val timestamp = startOfDay.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() // start time to timestamp
Log.d("Date:", "start date $timestamp")
Log.d("Date:", "start date parsed ${startOfDay.format(dateFormatter)}")
Output:
Start Date Timestamp : 1639506600000
Parsed TimeStamp: Wednesday, 15 December 2021 00:00:00
Edit : To get end of date time
val endOfDate: LocalDateTime = localDate.atTime(LocalTime.MAX)
val timestampEnd = endOfDate.atZone(ZoneId.of("UTC")).toInstant().epochSecond
Capture the current moment.
Instant now = Instant.now() ;
Understand that, for any given moment, the date varies around the globe by time zone. At one moment, it can be “tomorrow” in Tokyo Japan 🇯🇵 while simultaneously “yesterday” in Edmonton Alberta Canada 🇨🇦.
Specific time zone
Get the date in effect at that moment in a specific time zone. Here we use the time zone of India 🇮🇳.
ZoneId zKolkata = ZoneId.of( "Asia/Kolkata" ) ;
LocalDate todayKolkata = now.atZone( zKolkata ).toLocalDate() ;
Get the first moment of the date in that zone.
ZonedDateTime startOfTodayKolkata = todayKolkata.atStartOfDay( zKolkata ) ;
Get the count of whole seconds from first moment of 1970 UTC to that first moment of that date in Kolkata.
long secondsSinceEpochToStartOfTodayKolkata = startOfTodayKolkata.toInstant().getEpochSecond() ;
If you want to track the full length of the day, use Half-Open approach. In Half-Open, the beginning is inclusive while the ending is exclusive. So a full day starts at the first moment of one date and runs up to, but does not include, the beginning of the following day.
ZonedDateTime startOfTomorrowKolkata = todayKolkata.plusDays( 1 ).atStartOfDay( z ) ;
Track the full day as a pair of Instant objects, using the Interval class from the ThreeTen-Extra library.
Interval allDayTodayKolkata = Interval.between( startOfTodayKolkata , startOfTomorrowKolkata ) ;
UTC (offset of zero)
In contrast, determine the first moment of today’s date as experienced with an offset of zero hours-minutes-seconds.
LocalDate todayUtc = now.atOffset( ZoneOffset.UTC ).toLocalDate() ;
ZonedDateTime startOfDayUtc = todayUtc.atStartOfDay( ZoneOffset.UTC ) ;
long secondsSinceEpochToStartOfDayUtc = startOfDayUtc.toInstant().getEpochSecond() ;
Here is how can you can get the number of hours later time from current time in Kotlin:
https://stackoverflow.com/a/73050414/7126848

Kotlin convert DateTime to 10 digit TimeStamp

I'm trying to find out how I can convert DateTime to 10 digit timestamp in Kotlin (Android Studio), I can't find any equivalent of it in Kotlin.
For example:
I have a val with date-time value like :
val dateTime = "2020-12-13 17:54:00"
Now I want to convert it to 10 digit timestamp like "1607842496"
Please give me a simple sample to show how I can resolve this problem. Thanks in advance.
Use the SimpleDateFormat class to parse your date String to a Date object. You can then get the timestamp (in milliseconds) from that Date object like so:
val dateTime = "2020-12-13 17:54:00"
val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
val date = simpleDateFormat.parse(dateTime)
val timestamp = date?.time
Divide the timestamp by a 1000 to get the 10 digit (in seconds) timestamp.

Localized time with leading zero

Under my locale DateFormat.getTimeInstance(DateFormat.SHORT).format(...) gives me 8:28 AM. Is there any way to get localized time but with leading zero (that is, 08:28 AM in my case) - I mean without hardcoding pattern etc?
If you want to have 24H format time you can do something like this using kotlin extensions:
fun Long.formatTime(): String? {
val calendar = Calendar.getInstance()
calendar.time = Date(this)
val hour = calendar.get(Calendar.HOUR_OF_DAY)
val minute = calendar.get(Calendar.MINUTE)
return String.format("%02d:%02d", hour, minute)
}
EDITED
If you still did't find the solution
val dateFormat = SimpleDateFormat("hh:mm a", Locale.getDefault())
print(dateFormat.format(Date()))
This prints
08:24 AM

ThreeTenABP not parsing date

I am trying to convert ISO 8601 time into something human readable and in the local timezone of the Android device.
String date = "2016-09-24T06:24:01Z";
LocalDate test = LocalDate.parse(date, ISO_INSTANT);
But it returns:
method threw 'org.threeten.bp.format.DateTimeParseException' exception
From reading http://www.threeten.org/threetenbp/apidocs/org/threeten/bp/format/DateTimeFormatter.html#ISO_INSTANT it seems like what I'm doing should be possible.
What am I doing wrong?
Edit
Expanded exception error:
Unable to obtain LocalDate from TemporalAccessor: DateTimeBuilder[fields={MilliOfSecond=0, NanoOfSecond=0, InstantSeconds=1474698241, MicroOfSecond=0}, ISO, null, null, null], type org.threeten.bp.format.DateTimeBuilder
Edit 2
The solution is in the answer below. For anyone that stumbles across this, if you want to specify a custom output format you can use:
String format = "MMMM dd, yyyy \'at\' HH:mm a";
String dateString = DateTimeFormatter.ofPattern(format).withZone(ZoneId.systemDefault()).format(instant);
#alex answer is correct. Here is a working example.
Instant represents a point in time. To convert to any other local types you will need timezone.
String date = "2016-09-24T06:24:01Z";
This date string is parsed using the DateTimeFormatter#ISO_INSTANT internally.
Instant instant = Instant.parse(date);
From here you can convert to other local types just using timezone ( defaulting to system time zone )
LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
LocalDate localDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();
LocalTime localTime = instant.atZone(ZoneId.systemDefault()).toLocalTime();
Alternatively, you can use static method to get to local date time and then to local date and time.
LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
LocalDate localDate = localDateTime.toLocalDate();
LocalTime localTime = localDateTime.toLocalTime();
You need to use Instant.parse().
This will give you an Instant that you can combine with a time zone to create a LocalDate.
In Kotlin:
Converts to LocalDateTime directly based on your local time zone::
val instant: Instant = Instant.parse("2020-04-21T02:22:04Z")
val localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime()
Converts to Date and time separately based on your local time zone:
val localDate: LocalDate = instant.atZone(ZoneId.systemDefault()).toLocalDate()
val localTime: LocalTime = instant.atZone(ZoneId.systemDefault()).toLocalTime()

Categories

Resources