how to convert string to DateTime as UTC as simple as that - c#

assume I have this string :
How can I convert it to DateTimeOffset object that will have UTC time - means -00:00 as Time Zone - even if I run it on machine on a specific timezone?
Assume String:
"2012-10-08T04:50:12.0000000"
Convert.ToDateTime("2012-10-08T04:50:12.0000000" + "Z");
--> DateTime d = {10/8/2012 6:50:12 AM}
and I want it to be
DateTime d = {10/8/2012 4:50:12 AM}
as if it will understand I want the date as simple as it comes (BTW - my machine is in timezone +02:00)

Use DateTimeOffset.Parse(string).UtcDateTime.

The accepted answer did not work for me. Using DateTimeOffset.Parse(string) or DateTimeOffset.ParseExact(string) with the .UtcDateTime converter correctly changed the kind of the DateTime to UTC, but also converted the time.
To get to a DateTime that has the same time as the original string time, but in UTC use the following:
DateTime dt = DateTime.ParseExact(string, "yyyy-MM-ddTHH:mm:ss.fffffff",
CultureInfo.InvariantCulture);
dt = DateTime.SpecifyKind(dt, DateTimeKind.Utc);

I did this by checking the DateTimeKind. On my function, 2 different types of date-times are coming. What I want is to convert UTC time to local time from the below function. Input parameter date is always coming as UTC.
Eg inputs: 2021-01-19 07:43:00 AM and 01/07/2021 02:16:00 PM +00:00
public static DateTime GetDateTime(string date)
{
try
{
DateTime parsedDate = DateTime.Parse(date, GetCulture()); //invarient culture
if (parsedDate.Kind == DateTimeKind.Unspecified)
{
parsedDate = DateTime.SpecifyKind(parsedDate, DateTimeKind.Utc);
}
return parsedDate.ToLocalTime();
}
catch (Exception e)
{
throw;
}
}

var universalDateTime = DateTime.Parse(your_date_time_string).ToUniversalTime();

Using, DateTimeStyles.AssumeUniversal in DateTime.Parse(...) will do the job,
Ex:
DateTime.Parse("2023-01-02 9:26", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal)
then the parsed datetime will be in UTC

Related

How to convert this UTC datetime string to DateTime object c#

I have been trying to convert this string to a DateTime object in C#
2019-09-23T08:34:00UTC+1
I've tried using DateTime.Parse but it is throwing an exception for
"String was not recognized as a valid DateTime."
I'm sorry but you seem like a victim of garbage in, garbage out.
That's an unusual format, that's why before I suggest a solution for you, first thing I want to say is "Fix your input first if you can".
Let's say you can't fix your input, then you need to consider a few things;
First of all, if your string has some parts like UTC and/or GMT, there is no custom date and time format specifier to parse them. That's why you need to escape them as a string literal. See this question for more details.
Second, your +1 part looks like a UTC Offset value. The "z" custom format specifier is what you need for parse it but be careful, this format specifier is not recommended for use with DateTime values since it doesn't reflect the value of an instance's Kind property.
As a solution for DateTime, you can parse it like I would suggest;
var s = "2019-09-23T08:34:00UTC+1";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd'T'HH:mm:ss'UTC'z", CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal, out dt))
{
Console.WriteLine(dt);
}
which gives you 2019-09-23 07:34:00 as a DateTime and which has Utc as a Kind property.
As a solution for DateTimeOffset - since your string has a UTC Offset value you should consider to parse with this rather than Datetime
-, as Matt commented, you can use it's .DateTime property to get it's data like;
var s = "2019-09-23T08:34:00UTC+1";
DateTimeOffset dto;
if(DateTimeOffset.TryParseExact(s, "yyyy-MM-dd'T'HH:mm:ss'UTC'z", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dto))
{
Console.WriteLine(dto.DateTime);
}
which gives you the same result DateTime but Unspecified as a .Kind property.
But, again, I strongly suggest you to fix your input first.
Use TryParseExact to convert the string to datetime. Here is the sample code to covert the given format(s) to datetime
private static DateTime ParseDate(string providedDate) {
DateTime validDate;
string[] formats = {
"yyyy-MM-ddTHH:mm:ss"
};
var dateFormatIsValid = DateTime.TryParseExact(
providedDate, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out validDate);
return dateFormatIsValid ? validDate: DateTime.MinValue;
}
Then, use this function to convert the string. I am replacing UTC+1 to empty string
static void Main(string[] args) {
string strdatetime = "2019-09-23T08:34:00UTC+1";
DateTime dateTime = ParseDate(strdatetime.Replace("UTC+1", ""));
Console.WriteLine(dateTime);
}

DateTime parsing - unexpected result

I have datetime string
dateStr = "2017-03-21T23:00:00.000Z";
then I am calling
var date = DateTime.Parse(dateStr);
and unexpectedly my date equals
22.03.2017 00:00:00
I expected it to be 21.03.2017
What's going on here?
DateTime.Parse() is locale specific and will take into account your local time zone when parsing dates.
If you are in CET (Central European Time) during the winter your offset is one hour ahead of UTC. The date given is marked with a Z indicating it is in UTC, so DateTime.Parse() will adjust that to your local timezone.
There is an override that allows you to change that behaviour if you want, by specifying a specific DateTimeStyles enum. DateTimeStyles.AdjustToUniversal is what you are looking for as that should keep the DateTime as UTC.
And if you only want the date part afterwards, you can just call .Date on the DateTime object you got back from Parse()
So, something like this:
var date = DateTime.Parse(dateStr, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).Date;
if the date format does not change then you can use the below code to get date part from date string. But it is a bit risky due to its strict dependency on the input format.
string dateStr = "2017-03-21T23:00:00.000Z";
int year = Int32.Parse(dateStr.Substring(0, 4));
int month = Int32.Parse(dateStr.Substring(5, 2));
int day = Int32.Parse(dateStr.Substring(8, 2));
var date = new DateTime(year, month, day);
Console.WriteLine(date);
Because the format of type 'DateTime' variable is 'YYYY-MM-DD hh:mm:ss'.
If you run this code:
var dt = DateTime.Now;
Console.WriteLine(dt);
You'll see '24/03/2017 12:54:47'
If you have 'YYYY-MM-DD' format, add .ToString("dd-MM-yyyy"), then:
string dateStr = "2017-03-21T23:00:00.000Z";
var date = DateTime.Parse(dateStr).ToString("dd-MM-yyyy");
Result:'24-03-2017'

In C#, How to convert a date time string with timezone to DateTime? [duplicate]

I am trying to parse 11/23/2011 23:59:59 UTC +0800 as a c# datetime object but trying the standard datetime parse method or even the datetime exact parse I get invalid date.
Any ideas?
I would suggest you parse to a DateTimeOffset instead of a DateTime, as recommended in MSDN when using a time zone offset specifier in the format string:
using System;
using System.Globalization;
class Test
{
static void Main(string[] args)
{
string text = "11/23/2011 23:59:59 UTC +0800";
string pattern = "MM/dd/yyyy HH:mm:ss 'UTC' zzz";
DateTimeOffset dto = DateTimeOffset.ParseExact
(text, pattern, CultureInfo.InvariantCulture);
Console.WriteLine(dto);
}
}
You can then convert that to a DateTime value in UTC if you want, but there's no such thing as "a DateTime with an offset of 8 hours" - a DateTime is either regarded as universal, local or unspecified, with nowhere for a specific offset to be stored.
DateTime is a curious type in various ways, and can cause problems for the unwary developer.
Msdn for Format settings: https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
public class Program
{
public static void Main()
{
//original date
string _date = "Thu Jan 15 11:32:09 +0200 2015";
// Describes the date format
string _parsePattern = "ddd MMM dd HH:mm:ss zzz yyyy";
DateTimeOffset dto = DateTimeOffset.ParseExact(_date, _parsePattern, CultureInfo.InvariantCulture);
//last settings
Console.WriteLine(dto.ToString("dd.MM.yyyy hh:mm:ss",CultureInfo.CreateSpecificCulture("tr-TR")));
}
}
for extension method:
public static DateTime getDateFromFormat(this string _date, string _parsePattern)
{
DateTimeOffset dto = DateTimeOffset.ParseExact(_date, _parsePattern, CultureInfo.InvariantCulture);
return Convert.ToDateTime(dto.ToLocalTime());
}
For test: https://dotnetfiddle.net/xdnjGy
As written by James, you can try
var dt = DateTime.ParseExact(
"11/23/2011 23:59:59 UTC +0800",
"MM/dd/yyyy HH:mm:ss 'UTC' K",
CultureInfo.InvariantCulture);
You'll get a date in the "local" time.
I think you need to use ParseExact
http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx

datetime to string with time zone

I have a DateTime stored in universal time (UTC) of value 2010-01-01 01:01:01.
I would like to display it in EST in this format 2010-01-01 04:01:01GMT-04:00, however the 'K' formatter for timezone doesn't work in ToString
Use the "zzz" format specifier to get the UTC offset. For example:
var dt = new DateTime(2010, 1, 1, 1, 1, 1, DateTimeKind.Utc);
string s = dt.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss \"GMT\"zzz");
Console.WriteLine(s);
Output:
2009-12-31 19:01:01 GMT-06:00
I'm in the CDT timezone. Make sure the DateTime is unambiguously DateTimeKind.Utc.
If like myself you happen to need a format like 2018-03-31T01:23:45.678-0300 (no colon in the timezone part), you can use this:
datetime.ToString("yyyy-MM-ddTHH:mm:ss.fffzzz").Remove(26,1)
This method will return the specified time in Eastern Standard Time (as the question requested), even if EST is not the local time zone:
public string GetTimeInEasternStandardTime(DateTime time)
{
TimeZoneInfo easternStandardTime = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
DateTimeOffset timeInEST = TimeZoneInfo.ConvertTime(time, easternStandardTime);
return timeInEST.ToString("yyyy-MM-dd hh:mm:ss tt\" GMT\"zzz");
}
Note: I haven't tested this in a non-English OS. See the MSDN documentation on TimeZoneInfo.FindSystemTimeZoneById.
Something like this works. You could probably clean it up a bit more:
string newDate = string.Format("{0:yyyy-MM-dd HH:mm:ss} GMT {1}", dt.ToLocalTime(), dt.ToLocalTime().ToString("%K"));
I think you are looking for the TimeZoneInfo class (see http://msdn.microsoft.com/en-us/library/system.timezoneinfo_members.aspx). It has many static methods to convert dates between time zones.

C# Getting Just Date From Timestamp

If I have a timestamp in the form: yyyy-mm-dd hh:mm:ss:mmm
How can I just extract the date from the timestamp?
For instance, if a timestamp reads: "2010-05-18 08:36:52:236" what is the best way to just get 2010-05-18 from it.
What I'm trying to do is isolate the date portion of the timestamp, define a custom time for it to create a new time stamp. Is there a more efficient way to define the time of the timestamp without first taking out the date, and then adding a new time?
DateTime.Parse("2010-05-18 08:36:52:236").ToString("yyyy-MM-dd");
You should use the DateTime type:
DateTime original = DateTime.Parse(str);
DateTime modified = original.Date + new TimeSpan(13, 15, 00);
string str = modified.ToString("yyyy-MM-dd HH:mm:ss:fff");
Your format is non-standard, so you'll need to call ParseExact instead of Parse:
DateTime original = DateTime.ParseExact(str, "yyyy-MM-dd HH:mm:ss:fff", CultureInfo.InvariantCulture);
You could use substring:
"2010-05-18 08:36:52:236".Substring(0, 10);
Or use ParseExact:
DateTime.ParseExact("2010-05-18 08:36:52:236",
"yyyy-MM-dd HH:mm:ss:fff",
CultureInfo.InvariantCulture)
.ToString("yyyy-MM-dd");
DateTime date;
if (DateTime.TryParse(dateString, out date))
{
date = date.Date; // Get's the date-only component.
// Do something cool.
}
else
{
// Flip out because you didn't get a real date.
}
Get the .Date member on the DateTime
DateTime date = DateTime.Now;
DateTime midnightDate = date.Date;
use it like this:
var x = DateTime.Now.Date; //will give you midnight today
x.AddDays(1).AddTicks(-1); //use these method calls to modify the date to whats needed.
The best (and fastest) way to do this is to convert the date to an integer as the time part is stored in the decimal part.
Try this:
select convert(datetime,convert(int, #yourdate))
So you convert it to an integer and then back to a data and voila, time part is gone.
Of course subtracting this result from the original value will give you the time part only.

Categories

Resources