Parse Decimal Second by PostgreSQL - sql

I would like parse a String
'16:25:20.6598412Z'
as TIMESTAMP WITHOUT TIME ZONE
The function which I use is:
TO_TIMESTAMP('16:25:20.6598412Z', 'HH24:MI:SS.MSUS')
but the result is:
16:25:21.5002+01
this have not the same time:
16:25:20.6598412

You cannot use MS and US both in one to_timezone call - microseconds are miliseconds also (and a little more) so how engine would know how to parse the string?
Instead you should use
TO_TIMESTAMP('16:25:20.6598412Z', 'HH24:MI:SS.US')
also notice that microseconds due to reference is value in range of (000000-999999) so you can pass 6 digits as US
TO_TIMESTAMP('16:25:20.659841Z', 'HH24:MI:SS.US')
To loose timezone simply add ::timestamp without time zone; at the end of to_timestamp call
TO_TIMESTAMP('16:25:20.6598412Z', 'HH24:MI:SS.MSUS')::timestamp without time zone;

Related

bigquery converting string to time mm:ss

how can I convert the string "average_time_per_KM" to time in the formt of mm:ss?
I tryed using TIME and got an error 'Invalid time string "4:56"'Cast query to time format
is there a different function to cast in to mm:ss?
You can use any of below parse time that presented as string as minutes:seconds
PARSE_TIME("%M:%S", average_time_per_KM)
or
CAST(average_time_per_KM AS TIME FORMAT 'MI:SS')
You need to tell BQ what is the meaning of each digit in the string you give it.
For that you need to use the PARSE_TIME function:
SELECT PARSE_TIME("%M:%S", average_time_per_KM)
FROM `your.table`

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!

NSDate dateWithTimeIntervalSince1970 displays wrong timestamp to console

NSDate *createDate = [NSDate dateWithTimeIntervalSince1970:1376460694.103];
NSLog(#"createDate %#",createDate);
I am using the above code to get the current date and time,when I put break point at createDate,It shows correct time stamp value,but NSLog(#"createDate %#",createDate) statement is printing the date as 2013-08-14 06:11:34 +0000.
How to get the correct result?
The date is correct. When printing to the console the description of the date is used and that uses your system locale so it applies your time zone to the date before printing.
When you want to display the time you need to use a date formatter to convert the date into a string. The important part is setting the locale / time zone that the formatter uses.
Take a read of this and this.

Parsing Datetime

I have a date time as a string, eg. "2010-08-02", I'm trying to convert it to UTC with the following code snippet
DateTime.ParseExact("2010-08-02Z", "yyyy-MM-ddZ", CultureInfo.InvariantCulture)
When I print to the console, I get the following: 8/1/2010 5:00:00 PM.
Is there a reason why the date shows up as the date before the date I'm trying to parse? I could just add a day to this to advance to the original day, but I wanted to see if there's anything I'm doing wrong in the formatting that's causing this.
EDIT: I had a mixture of being correct and not :)
It's showing you the local time represented by the UTC string. It's annoying that DateTime doesn't make this sort of thing clear, IMO. Additionally, I don't think you want to use 'Z' as the format specifier for the time zone; that's not actually a valid format specifier; it should be 'z', - but that's meant for things like "+01:00". I think you should be using 'K'. Frankly it's not clear, but if you use 'K' it round-trips correctly, certainly ('Z' roundtrips too, but only because it ignores it, treating it as plain text).
You can fix it by just calling ToUniversalTime, or (preferred IMO) specifying DateTimeStyles.AdjustToUniversal as an extra argument:
DateTime dt = DateTime.ParseExact("2010-08-02Z", "yyyy-MM-ddK",
CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal);
The UTC of midnight for 2010-08-02 happens to be at 5pm on 2010-08-01.
If the original string is just a date in the format "2010-08-02" (without the Z), then why not just:
DateTime.SpecifyKind(
DateTime.ParseExact("2010-08-02",
"yyyy-MM-dd",
CultureInfo.InvariantCulture),
DateTimeKind.Utc);
ParseExact will presumably return a DateTime with Kind = Unspecified, and you can make it UTC or Local as you wish using SpecifyKind.