How to convert milliseconds to timestamp in kotlin programming - kotlin

how to convert milliseconds to timestamp in kotlin.
time in milliseconds : 1575959745000 to format: dd/MM/yyyy HH:MM:ss

EDIT: now, there is the kotlinx-datetime library
There is no pure Kotlin support for dates at the moment, only durations.
You will have to rely on the target platform's facilities for date/time parsing and formatting.
Note that, whatever platform you're targeting, it doesn't really make sense to convert a millisecond epoch to a formatted date without defining the timezone.
If you're targeting the JVM, then you can use the java.time API this way:
// define once somewhere in order to reuse it
val formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
// JVM representation of a millisecond epoch absolute instant
val instant = Instant.ofEpochMilli(1575959745000L)
// Adding the timezone information to be able to format it (change accordingly)
val date = LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
println(formatter.format(date)) // 10/12/2019 06:35:45
If you're targeting JavaScript, things get trickier. You can do the following to use some sort of default time zone, and some close-enough format (defined by the locale "en-gb"):
val date = Date(1575959745000)
println(date.toLocaleString("en-gb")) // 10/12/2019, 07:35:45
You have ways to specify the timezone according the standard JS API for Date.toLocaleString(). But I haven't dug much into the details.
As for native, I have no idea.

Related

Converting "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" and "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSX" to one common Timestamp for a SQL table

I have two different formats for data and I am trying to have a common format.
Format A
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
Sample time:
2020-09-10T22:40:58.807+00:00
Format B
"yyyy-MM-dd'T'HH:mm:ss.SSSSSSSX"
Sample time:
2020-07-23T02:46:04.0978382Z
I am trying to merge them into one common format and eventually use them for a SQL Dataframe with type Timestamp. I have been using SimpleDateFormat for format A, and for Format B I cannot parse with SimpleDateFormat as it doesn't support Nanoseconds, so instead have been using
val inFormat = DateTimeFormatter.ofPattern(timestampFormat)
val localDatetime = LocalDateTime.parse(timestampString, inFormat)
Timestamp.valueOf(localDatetime) // converting Datetime to timestamp
After using the above my Format B sample time is 2020-07-23 02:46:04.0978382 While format A using SimpleDateFormat is 2020-09-10 22:40:58.807
How can I create a common format for both A and B to be later used into a SQL table? My goal is for whats in format A matches what is in format B(granularity too).
Something that I am trying is using OffsetDateTime to convert both formats. With OffSetDateTime I will
import java.time.OffsetDateTime
val odt = OffsetDateTime.parse(2020-07-23T02:46:04.0978382Z)
println(odt)
In this case, seems like I would truncate offsetDatetime? Is this a good approach?
Thanks
You haven’t got two different formats. What you call format A and format B are both variants of ISO 8601 format, the international standard. OffsetDateTime parses the most common ISO 8601 variants as its default, that is, without any explicit formatter. Also both of your variants.
OffsetDateTime dateTimeA = OffsetDateTime.parse("2020-09-10T22:40:58.807+00:00");
System.out.println(dateTimeA);
OffsetDateTime dateTimeB = OffsetDateTime.parse("2020-07-23T02:46:04.0978382Z");
System.out.println(dateTimeB);
Output:
2020-09-10T22:40:58.807Z
2020-07-23T02:46:04.097838200Z
You also notice that no values have been truncated.
You probably don’t need to convert to a java.sql.Timestamp. That’s good because the Timestamp class is a hack on top of the already poorly designed java.util.Date class, and both those classes are long outdated. Assuming that you need a timestamp with time zone in SQL (recommended for timestamps), since JDBC 4.2 pass your OffsetDateTime to SQL. An example:
OffsetDateTime dateTimeA = OffsetDateTime.parse("2020-09-10T22:40:58.807+00:00");
PreparedStatement insertStmt = yourDatabaseConnection.prepareStatement(
"insert into your_table(your_timestamp_with_time_zone_column) values (?)");
insertStmt.setObject(1, dateTimeA);
int rowsInserted = insertStmt.executeUpdate();
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601
My answer to a related question: Getting the date from a ResultSet for use with java.time classes
You don't need a "common" format.
You have 2 options:
You can detect with regex what format your current input has.
Like:
def parse(inputString: String): Timestamp {
if(isFormatA(inputString))
parseFormatA(inputString)
else
parseFromatB(inputString)
}
You can improve it with regex pattern matching.
You can sequentially try both formats with exception handling or library that will return option.
Like:
def parse(inputString: String): Timestamp {
Try(parseFormatA(inputString))
.orElse(Try(parseFormatB(inputString)))
.get
}

Formatting js-joda Duration instance

I'd like to display a chrono of elapsed time since the beginning of an operation to a user. I create a Duration instance from a number of seconds, but then, I can't find a way to properly format it like 00:00:23. Do I have to manually get each time component (hours, minutes, seconds) and assemble them?
The Formatting section of the docs specifies that a DateTimeFormatter can only be passed to the format method of LocalDate, LocalTime, LocalDateTime, or ZonedDateTime instance, and Duration does not have such method.

VB.Net Convert time from UTC to Local

I am working on a news website and I am saving all dates in the database in UTC. Then, depending on the browser/machine location, I want to display the date/time correspondingly (Convert from UTC to the Local time of the machine/browser).
First of all, I would like to know if I am doing this the way it should be done or not (UTC dates in the database).
Second, I wonder why isn't it that straightforward to do so in VB.NET? Below are the approaches I tried but none worked as needed:
Approach 1:
TimeZoneInfo.ConvertTimeFromUtC
This kept returning the server time and not the client/machine time.
Approach 2:
Dim TimeZone As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Middle East Standard Time")
Dim Dated As DateTime = TimeZoneInfo.ConvertTimeFromUtC(TempDate, TimeZone)
This worked but not as intended. This converted the UTC date/time in the database to the Middle East Time Zone but any user from any other place in the world will only see the date/time in Middle East Time Zone and not in the actual timezone of his place. Also, I am not sure if the conversion considers DayLightSaving or not.
Approach 3:
I tried to fix this using JavaScript. I created a cookie that saves the offset from UTC and tried handling the offset in VB.NET and do the conversion.
<script>
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getTimeOffset() {
var offset = new Date().getTimezoneOffset();
setCookie("_tz", offset);
}
</script>
JavaScripts returns the correct Offset and I am saving this offset in a cookie. Since JavaScript launches after Page_Load, I am calling the JavaScript function getTimeOffset() on Page_Init:
ScriptManager.RegisterStartupScript(Me, Page.GetType, "Script", "getTimeOffset();", True)
The cookie is being created before the page is rendered and the offset stored in the cookie is correct (This is what I actually want!). The problem here is on the first load. VB.NET reads the cookie value as empty string on the first load. On the second Page_Load onwards, VB.NET reads the cookie value and does the conversion correctly.
Approach 4
Tried to get the offset using all the examples in this fiddle but the offset is always 0 which is wrong.
Summary
I wonder if there is any function I missed in VB.NET to avoid all that hassle. Shouldn't it be an easy task to convert date/time from UTC to Local?
Please let me know if there is anything I am doing wrong or if there is a better alternative.
Your back-end code doesn't know anything about the time zone of the browser. It doesn't matter what language you are using, only the browser will know anything about the user's time zone.
When .Net code (regardless of VB or C#) refers to "local", it means the local time zone of where that code is running. In other words, in an ASP.Net web application, that's the local time zone of your server, not of the user. Generally speaking, the server's local time zone is usually irrelevant.
To achieve your goal, break the problem up into two parts.
Get the user's time zone in the browser, send it to the server.
Convert time on the server, using the time zone passed in.
For step 1, read this answer I posted to a different question. Note that the output will be an IANA time zone identifier. Do not pass a numeric offset, as it does not carry enough information to properly convert different points in time (consider daylight saving time, and other anomalies with time zones).
For step 2, you'll need to choose between one of these approaches:
You can use the IANA time zone identifier natively with TimeZoneInfo if you're running .NET Core on a non-Windows OS, or with the Noda Time library on any platform.
You can convert the IANA time zone identifier to a Windows time zone identifier using my TimeZoneConverter library, and then you can use the result with the TimeZoneInfo class on Windows.
One little thing: You used TimeZoneInfo.ConvertTimeToUtc, where I think you meant TimeZoneInfo.ConvertTimeFromUtc. Be careful of the directionality of the conversions.
I'll also point out that there's an alternative approach, which is to pass the UTC timestamp all the way down to the browser, and just convert from UTC to local time in JavaScript. Then you don't need to do any time zone detection at all.

convert date in 2015-05-09T09:00:12.123462000 to unix timestamp in hive

I want to convert the date which is in '2015-05-09T09:00:12.123462000' format to the unix timestamp in hive. The UNIX_TIMESTAMP('2015-05-09T09:00:12.123462000') doesn't work. I am not sure how i can convert this. I need this to compare two dates in different format. I am converting both the dates to unix timestamp but this fails. can someone please help with this.
Thanks
Your input uses the full ISO 8601 format, with a "T" between date and time, and fractional seconds. Hive expects an SQL format (i.e. with a space between date and time) as seen in java.sql.Timestamp and ODBC, with or without fractional seconds, as stated in the Hive documentation.
Just apply some very elementary string massaging -- then "cast" the String to a Hive Timestamp. And pleeease forget that lame roundtrip to and from UNIX_TIMESTAMP:
cast(regexp_replace('2015-05-09T09:00:12.123462000', 'T',' ') as Timestamp)
The Answer by Samson Scharfrichter is correct and should be accepted. I'll just add some words about java.time types.
Converting between String ↔ java.time.Instant
The java.time classes supplant the troublesome old legacy date-time classes such as java.sql.Timestamp.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Your input string complies with the ISO 8601 standard. The java.time classes use ISO 8601 formats by default when parsing/generating strings that represent date-time values. So no need to specify a formatting pattern. You can directly parse your string as an Instant object.
Your input string lacks an indication of offset-from-UTC or time zone. If it was intended to be in UTC, append a Z for Zulu which means UTC.
Instant instant = Instant.parse( "2015-05-09T09:00:12.123462000" + "Z" );
You can generate such a string, merely call toString. The default formatter used by toString prints the decimal fraction in groups of three digits as needed. In this example the last three digits are zeros so they are omitted.
String output = instant.toString();
2015-05-09T09:00:12.123462Z
To make this into SQL-style string expected by Hive, replace the T with a SPACE and remove the Z.
String inputForHive = output.replace( "T" , " " ).replace( "Z" , "" );
2015-05-09 09:00:12.123462
Conversion from numbers
Hive also provides for conversions from:
integer numberCount of whole seconds from the Unix/Posix epoch of beginning of 1970 UTC (1970-01-01T00:00:00Z).
floating-point numberSame as above but with a fractional second in up to nanoseconds resolution.
The second one I suggest you avoid. The floating-point types such as float, Float, double, and Double in Java purposely trade off accuracy for faster execution time. This often results in extraneous digits at the end of your decimal fraction. If you need fractional second, stick with the String type & Instant object.
The first one can easily be obtained from an Instant by calling the getEpochSecond method. Of course this means data loss as this method leaves behind any fractional second.
long secondsSinceEpoch = instant.getEpochSecond();
Going the other direction.
Instant instant = Instant.ofEpochSecond( secondsSinceEpoch );
Comparing
Once you have your Instant objects, you can compare with methods such as compareTo, equals, isBefore, isAfter.
Boolean happenedBefore = thisInstant.isBefore( thatInstant );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
If available you can simply use the following syntax
1) check whether what UDFs are available in your hive install?
show functions;
2) if seen from_unixtime() function then:
from_unixtime(your_timestamp_field)
This will solve the problem!
Please add comments, if you like my answer!

Is there an easier way of getting Utc time in gamemaker?

The only way I have found is this:
round(date_second_span(date_create_datetime(1970,1,1,0,0,0),date_current_datetime()));
GM has not special functions for working with UTC time, so you can use scripts for convert. For back convert you can use this, if need:
/// date_timestamp(timestamp)
// Convert UNIX time to GMS time
var t = date_inc_second(25569+1, argument0);
return date_inc_day(t, -1);
+1 and -1 needed because GMS has a bug