Converting seconds to time of day - android

I have an app on iOS and am working on porting over to android. I am having an issue with handling the time.
On iOS I store points of time using:
Int(NSDate().timeIntervalSince1970-0.5)
and Convert it to HH:MM:SS using:
private let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
return dateFormatter.string(from: Date(timeIntervalSince1970: value))
On Android(Kotlin) to store the point of time I use: System.currentTimeMillis()/1000
And for conversion:
LocalTime.MIN.plus(Duration.ofSeconds(xVal)).toString())
The issue is that the value after being converted is 6 hours ahead(could be more or less but I only look at the HH:MM:SS). As far as I can tell, the way that I get the time on android is correct and I think the issue lies in when I am converting it. I have looked around for more methods of converting time since an an interval to time of day but I could not get it to work. Most posts are just converting seconds to HH:MM:SS and so those are right out of the question. What would the equivalent to my iOS code be?
EDIT
I've also tried using this method to convert it still is 6 hours off even though I am giving it a timezone:
val cal = Calendar.getInstance()
cal.timeInMillis = xVal * 1000L
cal.timeZone = TimeZone.getTimeZone(TimeZone.getDefault().displayName)
Log.i("This is the cal value",cal.get(Calendar.HOUR_OF_DAY).toString())

val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
val date = sdf.format(Date(alarm.getNextTrigger()));

Related

How to get epoch milis from a date (LocalDate)

I have a month July 2022 for example, I want get epoch milis for the first day of the month
1st July 2022 at midnight.
from the month I was able to get the 1st July 2022, but how to convert it into epoch milis for 1st July 22 midnight
val datey = "July/2020"
val dateFormaty = DateTimeFormatter.ofPattern("MMMM/yyyy")
val yearMonthy = YearMonth.parse(datey, dateFormaty)
val parsedDatey = yearMonthy.atDay(1)
I get 2022-07-01 for parsedDate, I want to get the date time for this date in epoch milis
Thanks
R
Like I mentioned, LocalDate does not actually store any time information whatsoever, so transforming it to epoch isn't possible. Technically. Yet it is with some possible inacuracies.
How about something like this:
make the following extension function
fun LocalDate.toDate(): Date = Date.from(this.atStartOfDay(ZoneId.systemDefault()).toInstant())
Note that it uses the system default timezone for this, to provide the necessary information.
then just use it.
val myDate = myLocalDate.toDate()
which would in your case, be parsedDatey.toDate()
But, we don't really even need the Date here. Lets avoid casting the LocalDate to Date then getting the epoch milli from there, and just do it from the provided Instant instead.
So the real answer to your question is this:
fun LocalDate.getEpochMillis(): long = this.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()
// call this in your parsing method you posted
parsedDatey.getEpochMillis()

How it works MaterialDatePicker in Android?

I have some doubts about how it works the Calendar library in Android.
I have implemented a listener to get the selected date in the MaterialDatePicker. With the method addOnPositiveButtonClickListener, I get the date selected in milliseconds but I need to transform these milliseconds to a Date object, BUT! whenever I transform this millisecond to a Date object, I am not getting the right value.
For example, if I select 03/24/2021, when I create a new Date object with the correspondent millisecond I get the next Date -> 03/23/2021.
I am trying different solutions I find in different posts but no one works fine for me.
I am trying to use Calendar but is not working properly either.
fun Long.toDate() : Date {
val calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
calendar.timeInMillis = this // calendar.time.time = this
return calendar.time
}
and also try it out with different timeZone
fun Long.toDate() : Date {
val calendar = Calendar.getInstance(TimeZone.getDefault())
calendar.timeInMillis = this // calendar.time.time = this
return calendar.time
}
I have also try to save the millisecond on my Calendar instance with calendar.time.time but also is not working for me.
It is so curious because if I set the next values on my device:
Time zone in New Zealand (GMT+13:45) at 10:00 AM,
I select 03/02/2021, so should return the same date.
For this specific example is working fine (I am in Madrid, Spain GMT+01:00) and is returning the date 03/02/2021.
If it was working bad, should returns 02/02/2021, but for this timeZone is working fine.
But, if I change my device values to:
Time zone to Colombia (GMT-05:00) and I set my device time to 10:00 PM.
I select the same date, 03/02/2021, it should return the same date.
In this case, is returning me the day before, 03/01/2021.
Why MaterialDatePicker is working so bad and how can I fix that without doing so badly tricky code?
I saw it can be fixed used SimpleDateformat, but I would like to keep the timeZone and do it a good way, or at least the best way...
Thanks in advance!

Conversion of date and time to unix timestamp - kotlin

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.

getting local time on Android

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.

Get days until date based on timezone on phone

I´ve been trying to figure this out for a while but can not wrap my head around it.
I´m working on an android app and i want to display left to a specific date, and i want the number of days based on what time zone i have set on my phone.
I have Joda Time in my app and the information i have is for example:
2013-05-05 9.00PM the time is in PST (GMT-8) timezone, i have no clue how to do this and i have searched both on google and SO but can not get a clear answer.
EDIT
I managed to solve my problem with code found here on SO
String dateString = airDate + " " + airTime.toUpperCase();
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd K:mma");
sourceFormat.setTimeZone(TimeZone.getTimeZone("GMT-8"));
Date parsed;
parsed = sourceFormat.parse(dateString);
TimeZone tz = TimeZone.getDefault();
SimpleDateFormat destFormat = new SimpleDateFormat("yyyy-MM-dd");
destFormat.setTimeZone(tz);
result = destFormat.format(parsed);
However I found out that the times i first got isn´t correct and I now get the time zone in the format GMT-5 +DST. And I dont´t know what to do with the +DST if setting the time to 20:00 and using GMT-5 in my TimeZone.getTimeZone the time returned is 22:00 which is "wrong" since I live in sweden. I would appreciate any help with this.
If you could settle for a string that looks like "in 2 days", then you should be able to use DateUtils.getRelativeTimeSpanString().

Categories

Resources