VB.Net Convert time from UTC to Local - vb.net

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.

Related

How to convert milliseconds to timestamp in kotlin programming

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.

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

Get time for friends recent checkin

I'm using /checkins/recent endpoint. I was trying to get the check-in time. I find a json object createdAt. is that related with time ?
So, my question is how can I get the time from recent check-ins.
The Foursquare API docs for checkin object clearly state that createdAt represents the unix epoch time when the object was generated(time of activity). So, you can get the UTC time from the epoch. Add in the time zone offset, it denotes the minutes you need to add in the time to get local time.For example, the example checkin object in your question is from Bangladesh, so it has a offset of 360.
You haven't mentioned the language but from your tag list, I am assuming you have used Ruby so a simple way to do this in ruby would be.
require 'date'
Time.at(your_createdAt_value).utc.to_datetime
#For example from your created at value
Time.at(1389630660).utc.to_datetime
#This will make a datetime object of value 2014-01-13T16:31:00+00:00
For getting local time you can use the value of timeZoneOffset.
#To get local time add in the timeZoneOffSet
Time.at(your_createdAt_value).utc.to_datetime+Rational(timeZoneOffset_value,1440)
#The 1440 value is the number of minutes in a day. Rational calculates
#the fraction of the day by using the two values and adds it to the datetime object.
#for example,
Time.at(1389630660).utc.to_datetime+Rational(360,1440)
#This will make a datetime object of value 2014-01-13T22:31:00+00:00
You can format the object to the value you want by using formatting methods.

VB.net Time Zone Issues

I have a legacy application that uses the windows time zone information for calculating dates. For example, 35 = East Coast, 20 = central, 15=mountain. Here is the current function. It takes a date with a timezone and converts it to the timezone passed in. This works just fine on xp, but it crashes on Windows 7. I am guessing it has to do with the win32 portion of it or Windows 7 handles time zones differently.
I would prefer not to change the format of the time zone as that could cause some issues. The code is vb.net and I did not write it.
Public Shared Function ConvertTime(ByVal time As Date, ByVal timeZone As Integer) As Date
Dim UtcNow As Date = time.ToUniversalTime
Dim selectedTimeZone As TimeZones.Win32.Win32TimeZone = TimeZones.Win32.TimeZones.GetTimeZone(timeZone)
Return selectedTimeZone.ToLocalTime(UtcNow)
End Function
Anyone have this issue before?
Dim selectedTimeZone As TimeZones.Win32.Win32TimeZone =
TimeZones.Win32.TimeZones.GetTimeZone(timeZone)
In VB.NET you should be using the following class to replace Win32TimeZone
MSDN TimeZone Class (System)
Refer to the link i provided above to see the correct way of using the TimeZone Class in VB.NET.
It appears to not wont work due to TimZones.Win32.Win32TimeZone not being a valid class of .NET
That Timezones library is not a in the .NET BCL. Contact the author of your Timezones library for help.

How do you return the system time zone as a string?

I have an app where I set time zones for various cities around the globe. I have no problem doing this and it works great. When the app first loads, it finds your current location (lat & long) and sets the time zone using the device default time zone. I need to return the default time zone in a string, so I can display it. I don't want "GMT" or "EDT", I would like it in the format of "America/New_York" or 'Europe/London". Any ideas?
It sounds like you want this:
NSString *timeZoneName = [[NSTimeZone localTimeZone] name];
That returns "America/New_York" for me, here in the EST time zone.
Or given any NSTimeZone *tz you can get its [tz name], which is the conventional name you are looking for (e.g. "Asia/Tokyo" or "Europe/London".
Look at +[NSTimeZone knownTimeZoneName] for a list of possible names.
I hope that helps.
I don't think there is an object that automatically correlates the time zone to a physical place.
I see you've tagged this objective-c, but in C# you could do something simple like this:
public Enum TimeZone
{
[Description("New York")]
EDT,
[Description("Los Angeles")]
PST
}
public static string GetDescription(Enum value)
{
FieldInfo fi= value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
return (attributes.Length>0)?attributes[0].Description:value.ToString();
}
i'm not sure how easily portable this is to objective-c, and it does require using the reflection library in C#.
Well, you're making the assumption that EDT is the same time zone as America/New_York. It isn't. :) Yes, they're the same UTC offset, but as far as your system is concerned, they are defined independently. There's no strong association between them that Cocoa knows about.
As well, if the user gives you EDT, do you return New_York? Toronto? Panama? There's not a 1:1 correspondence. Oh, and: EDT isn't even unique to a single UTC offset. Australian Eastern Daylight Time is also abbreviated EDT, I'm told by the Cocoa docs.
There is a [NSTimeZone abbreviationDictionary] map between abbreviations and long names, but again, they're arbitrarily chosen when there's more than one association (such as New York and Panama.)
What is it you're trying to accomplish in a broader sense? What's your goal? Tell us and we may be able to suggest an alternate way to achieve it. :)