0

The problem

I have hosted a Razor pages web app on a cloud server which happens to be on GMT-8 and when I save data is uses the server side time. The client side datetime is on GMT+1.

Question

How can I change the default datetime value inside the app, so that it matches the client side?

I mean that when I use DateTime.Today, it should use the GMT+1 automatically (I don't want to use .AddHours(+9) because it causes problems in data viewing)

Further explanation

The server helpdesk, advises us that to make this possible I have to insert the code below, somewhere in the app, but I don't know where.

Is there a simpler or better way to do this, without javascript, with just C#?

The code suggested by server's helpdesk:

<script language="C#" runat="server">
protected DateTime GetCurrentTime()
{
    DateTime serverTime = DateTime.Now;
    DateTime _localTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(serverTime, TimeZoneInfo.Local.Id, "Central Europe Standard Time");
    return _localTime;
} 

protected void Page_Load(object sender, EventArgs e)
{
    Response.Write(GetCurrentTime());
}
</script>
3
  • I know. But, this is exacty what they put on their FAQ page. I just copy/pasted the code, literally.
    – Fillo
    Feb 27 at 13:27
  • If you want your host (server) to use GMT+1, I believe that's something you'd have to configure on the server - not in your app
    – marc_s
    Feb 27 at 13:30
  • See this response here - basically it says: Sorry there is no way in .NET to change the time zone globally.
    – marc_s
    Feb 27 at 13:32

2 Answers 2

0

By seeing that there is no straight way to do this. I managed to find a workaround, it is a bit longer but the result is the same.

All i had to do was, replace (on each page of the app front/backend):

@Datetime.today...,

with

@DateTime.UtcNow.Date...

Hope it helps.

0

You can use NodaTime library to convert current time in any timezone,
just pass current server universal time to this method:

public DateTime ConvertToTimeZoneFromUtc(DateTime utcDateTime, string timezone= "Asia/Kolkata")
{
    var easternTimeZone = DateTimeZoneProviders.Tzdb[timezone];
    return Instant.FromDateTimeUtc(utcDateTime)
                    .InZone(easternTimeZone)
                    .ToDateTimeUnspecified();
}

usage:

string zoneID = "Asia/Kolkata";
var date = ConvertToTimeZoneFromUtc(DateTime.Now.ToUniversalTime(), zoneID);

here's list of possible zone IDs: https://nodatime.org/TimeZones

Ref: https://blog.nitinsawant.com/2021/02/c-get-current-time-in-any-timezone.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.