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.
Related
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()
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
}
I am attempting to convert a timestamp into a date, which I am then putting into the query parameters of a request.
Here is the function that converts a timestamp into a date:
override fun fromTimestamp(timestamp: Long): String {
val tz = TimeZone.getTimeZone("UTC")
val calendar = Calendar.getInstance(tz)
calendar.timeInMillis = timestamp
// Quoted "Z" to indicate UTC, no timezone offset
val df = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
df.timeZone = tz
return df.format(calendar.time)
}
This seems to work perfectly fine when my device is set in English, after URL encoding the date, this is what appears in the parameters: 1970-01-01T00%3A00%3A00.000Z
Now, if my device is set in Arabic, the URL encoded date looks like this: %D9%A2%D9%A0%D9%A1%D9%A8-%D9%A1%D9%A0-%D9%A1%D9%A7T%D9%A1%D9%A9%3A%D9%A4%D9%A7%3A%D9%A1%D9%A9.%D9%A0%D9%A8%D9%A2Z
I can only assume that all of those characters, that are suppose to be integers, that are encoded are Arabic characters depicting a date
After some googling, I found this discussion which says to initialize the Calendar with a Locale from the US. But looking at the code above, you notice the calendar is being initialized with a UTC timezone.
I would think that a calendar instanced from a UTC timezone would kick out integers instead of a specific language's characters depicting integers, but I'm not entirely sure how the Android system works with that.
Any idea on how I can modify my function to represent calendar dates with integers no matter what the Locale is?
My bet goes for
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US)
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.
Every time I try to get the current time (I have a button for that, lets call it "botonGuardarEstado") I get the same hours and minutes. What I have noted is that the time I got is the time when I opened the app. What I mean is, if I opened the app at 7:10 a.m. and press the button at 7:12 a.m., I get 7:10 a.m. Here is my code:
DateFormat formatoFecha = new SimpleDateFormat("HH:mm dd/MM/yyyy");
String fecha = formatoFecha.format(Calendar.getInstance().getTime());
I am not getting weird values like different years or anything like that, and the format works well, the problem is that i get the same hours:minutes everytime i push the button. I alredy tried different ways of getting the date and time, things like Date(), or even getting only the hours and minutes using something like this
Calendar cal = Calendar.getInstance();
int mins = cal.get(Calendar.MINUTE);
but still got the same values.
I have the following class
private class InfoArchivo {
String temperatura, humedad, gas, humo, iluminacion, riego, ventilacion, fecha;
public InfoArchivo(String temperatura, String humedad, String gas, String humo, String iluminacion, String riego, String ventilacion, String fecha){
this.temperatura = temperatura;
this.humedad = humedad;
this.gas = gas;
this.humo = humo;
this.iluminacion = iluminacion;
this.riego = riego;
this.fecha = fecha;
if(!ventilacion.equals("0"))
this.ventilacion = "1";
else
this.ventilacion = "0";
}
I have an array of instances of that class. What i am trying to do is write a csv file using the array. Every other data (temperatura, humedad, etc) is correct. The only thing causing trouble is the date (fecha). The creation of the csv file is done until i press another button. When i press the botonGuardarEstado button i get the date, make an instance of the class InfoArchivo and add it to the array
EDIT: Also tried with this but still have the same issue:
Instant instant = Instant.now();
ZoneId zoneId = ZoneId.of("America/Guatemala");
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, zoneId);
DateTimeFormatter formato = DateTimeFormatter.ofPattern("HH:mm dd/MM/yyyy");
String fecha = zdt.format(formato);
Not a date-time problem
Your code as shown is correct.
So your problem must be happening elsewhere in your app. Perhaps you are not correctly feeding the new String (fecha) to the user interface. Or perhaps you need to do something to refresh the display of that new String’s value. We cannot help you further as you did not provide that other code.
java.time
By the way, you are using outmoded classes. The old date-time classes that have proven to be so confusing and troublesome have been supplanted by the java.time framework. See the Oracle Tutorial.
Java 8 and later: The java.time framework is built-in.
Java 7 & 6: Use the backport of java.time.
Android: Use this wrapped version of that backport.
Instant
An Instant is a moment on the timeline in UTC with resolution up to nanoseconds.
Instant instant = Instant.now(); // Current moment in UTC.
Time Zone
Apply a time zone (ZoneId) to get a ZonedDateTime. If you omit the time zone your JVM’s current default time zone is implicitly applied. Better to specify explicitly the desired/expected time zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or "Asia/Kolkata", "Europe/Paris", and so on.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
Generating Strings
You can easily generate a String as a textual representation of the date-time value. You can go with a standard format, your own custom format, or an automatically localized format.
ISO 8601
You can call the toString methods to get text formatted using the common and sensible ISO 8601 standard.
String output = instant.toString();
2016-03-19T05:54:01.613Z
Custom format
Or specify your own particular formatting pattern with the DateTimeFormatter class.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy hh:mm a" );
Specify a Locale for a human language (English, French, etc.) to use in translating the name of day/month and also in defining cultural norms such as the order of year and month and date. Note that Locale has nothing to do with time zone.
formatter = formatter.withLocale( Locale.US ); // Or Locale.CANADA_FRENCH or such.
String output = zdt.format( formatter );
Localizing
Better yet, let java.time do the work of localizing automatically.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM );
String output = zdt.format( formatter.withLocale( Locale.US ) ); // Or Locale.CANADA_FRENCH and so on.