Reputation: 5801
Here is my code:
DateTime dateTime;
string str = "2016-02-11 23:02:30 -0500";
if (!DateTime.TryParse(str, out dateTime))
{
}
I am receiving {2/12/2016 7:02:30 AM}
as dateTime result. But I want to get 2/11/2016
, is it possible?
Upvotes: 1
Views: 111
Reputation: 98848
Since your string has UTC Offset value, I would parse it to DateTimeOffset
instead of DateTime
.
DateTimeOffset dto;
string str = "2016-02-11 23:02:30 -0500";
if (DateTimeOffset.TryParse(str, CultureInfo.InvariantCulture, DateTimeStyles.None, out dto))
{
//Success
}
Now you have a DateTimeOffset
as {11.02.2016 23:02:30 -05:00}
and you can use it's .DateTime
property which returns 11.02.2016 23:02:30
.
Upvotes: 0
Reputation: 3641
I think you are looking for TimeZoneInfo
:
DateTime dateTime;
string str = "2016-02-11 23:02:30 -0500";
if (!DateTime.TryParse(str, out dateTime))
{
// error
}
dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified);
var serverTimeZone = TimeZoneInfo.Local; // Server time zone
var allTimeZones = TimeZoneInfo.GetSystemTimeZones(); // Time zone list
var clientTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Hawaiian Standard Time");
// DateTime in server time zone
var dateTimeZone = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dateTime, clientTimeZone.Id, serverTimeZone.Id);
Take a look at this fiddle: https://dotnetfiddle.net/Apx51v
Note:
And remember, DateTime
doesn't contains time-zone information.
"A developer is responsible for keeping track of time-zone information associated with a DateTime value via some external mechanism" DateTime in .NET
Upvotes: 1
Reputation: 299
You need to use DateTimeOffset.Parse() to parse string into DateTimeOffset object with represented offset and than format it to string without it("yyyy-MM-dd HH:mm:ss" in example)
Upvotes: 0