so i have been trying to convert date time which is saved in DB in utc format. AddedDate: 2022-08-09 12:28:19.717 Now i want to convert it into ist in a format like this: Mon, 09 Aug 2022 05:58 PM
i am using:
Posted on : @( TimeZoneInfo.ConvertTimeFromUtc(Model.AddedDate, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time")))but it was giving me the same format which is saved in database. (i was rendering the date in view)
CodePudding user response:
Just try to use formatted string. Like this:
Model.AddedDate.ToString("ddd, dd MMM yyyy hh:mm:ss", CultureInfo.InvariantCulture);
CodePudding user response:
Try this You have to convert string to datetime object before you convert it to UTC
string date = "2022-08-09 12:28:19.717";
DateTime localDateTime = DateTime.Parse(date);
DateTime utcDateTime = localDateTime.ToUniversalTime();
string nzTimeZoneKey = "India Standard Time";
TimeZoneInfo nzTimeZone = TimeZoneInfo.FindSystemTimeZoneById(nzTimeZoneKey);
//Console.WriteLine(nzTimeZone);
DateTime nzDateTime = TimeZoneInfo.ConvertTimeFromUtc(localDateTime, nzTimeZone);
Console.WriteLine(nzDateTime.ToString("ddd, dd MMM yyyy hh:mm:ss tt", CultureInfo.InvariantCulture));
The one liner
((DateTime)TimeZoneInfo.ConvertTimeFromUtc(DateTime.Parse("2022-08-09 12:28:19.717").ToUniversalTime(), TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"))).ToString("ddd, dd MMM yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);