I want method which returns the string datetime in target locale format by taking the UTC DateTime and UTC DateTime offset in c#, here is the example code
public string ConvertToTargetTimeZone(DateTime utcDateTime, int timeDifference)
{
string targetDateTime = string.Empty;
targetDateTime = utcDateTime.AddMinutes(-timeDifference).ToString(dateTimeFormat);
return targetDateTime
}?
return the target datetime in target locale format, for example, if I have -330 minutes offset for India and India datetime format is "dd/MM/yyyy" then it will return datetime in above format.
In short i want to find culture based on timeDifference
then culture return me the datetimeformatinfo
Just use this method. It will return you local timezone date in datetime format.
protected DateTime GetCurrentTime()
{
DateTime serverTime = DateTime.Now;
DateTime _localTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(serverTime,
TimeZoneInfo.Local.Id, "Indian Standard Time");
return _localTime;
}
Enjoy :)
Thanks for asking a question here.
I tried to run above code, and it is returning the desired results for me, let me tell you what I entered and what was the output
public ActionResult Index()
{
//Calling Function for testing
var TestDate= ConvertToTargetTimeZone(DateTime.UtcNow, 330);
return View();
}
public string ConvertToTargetTimeZone(DateTime utcDateTime, int timeDifference)
{
string targetDateTime = string.Empty;
targetDateTime = utcDateTime.AddMinutes(-timeDifference).ToString("dd/MM/yyyy");
return targetDateTime;
}
So in my case, input was:
UTCDatetime: 8/3/2017 8:05:02 AM, timeDifference: 330
Output:
targetDatetime: 03/08/2017
Looks like it is already solved.
Another method can be
//Example input is : 2012-09-19 01:27:30.000, which has unspecified timezone, so you can use
DateTime convertedDate = DateTime.Parse(dateStr);
var kind = convertedDate.Kind; // will equal DateTimeKind.Unspecified
//Specify kind in it if you know, suppose it is UTC
DateTime convertedDate = DateTime.SpecifyKind(
DateTime.Parse(dateStr),
DateTimeKind.Utc);
var kind = convertedDate.Kind; // will equal DateTimeKind.Utc
//Now call .ToLocalTime()
DateTime dt = convertedDate.ToLocalTime();
//Now to convert it into specific format like "dd/MM/yyyy"
targetDateTime= dt.ToString("dd/MM/yyyy hh:mm");
return targetDateTime; // Output will be 19/09/2012 06:57
That's it,you are done.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly