c# Parsing UTC datetime - c#

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

Related

How to Convert a string "dd/mm/yyyy HH:MM:SS" to "HH:MM" for on-line Test Duration?

Code :-
public string TestDuration { get; set; }
TestDuration =DateTime.Parse(dr.TestDuration.ToString()).ToShortTimeString() ;
I have a string of the format dd/mm/yyyy HH:MM:SS am/pm, it display date and time in my view, I need hours and minutes for online test duration in format hh:mm.
Example: testduration= 2hr or 2:30 mins
i have a string of type DateTime
That's not possible. You either have string or have DateTime. Your variable type can't be both of them.
You can format your DateTime with HH:mm format like;
var result = DateTime.Parse(dr.TestDuration.ToString())
.ToString("hh:mm", CultureInfo.InvariantCulture);
You didn't mentioned it but, on the other hand, your dr.TestDuration already might be a DateTime. You might wanna format this value instead to generate it's string representation, parsing it to DateTime and generate it's string representation again.
var result = dr.TestDuration.ToString("hh:mm", CultureInfo.InvariantCulture);
After your edit:
Since your TestDuration string and it has "dd/MM/yyyy HH:mm:ss tt" format, you need to parse it to DateTime and generate it's string representation with hh:mm format.
TestDuration = DateTime.ParseExact(dr.TestDuration, "dd/MM/yyyy HH:mm:ss tt",
CultureInfo.InvariantCulture)
.ToString("hh:mm", CultureInfo.InvariantCulture);

Convert custom date to mysql datetime

I have a custom date format that I want to convert to Datetime so I can then insert into my database, I tried using Datetime.ParseExact() But I think I'm misunderstanding something as the code throws a System.FormatException.
I have the following date format from a csv
> 6/11/2014 9:00
and I wish to convert it to the mysql datetime format
> 0000-00-00 00:00:00 OR yyyy-MM-dd HH:mm:ss
Notice they haven't included the seconds in the original date so I am unsure (without appending them to the end) how to set all records to just have "00" for seconds as it is not available.
I tried the following which throws an exception
DateTime myDate = DateTime.ParseExact("6/11/2014 9:00", "yyyy-MM-dd HH:mm",
System.Globalization.CultureInfo.InvariantCulture);
first thing you need to convert string to date time and than convert datetime tos tring
string strd = "6/11/2014 9:00";
DateTime dt ;
//convert datetime string to datetime
if(DateTime.TryParse(strd, out dt))
{
//convert datetime to custom datetime format
Console.WriteLine("The current date and time: {0: yyyy-MM-dd HH:mm:ss}",
dt); ;
}
output
I know this is late to answer that but I'm really surprised none of answer consider to use IFormatProvider to prevent a possible parsing error because of / format specifier or considering your string is a standard date and time format for your CurrentCulture or not so you can or can't use DateTime.TryParse(string, out DateTime) overload directly.
First of all, let's look at what DateTime.ParseExact documentation says:
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly or an exception is thrown.
In your case, they don't match. You should use d/MM/yyyy H:mm format to parse your example string with a culture that have / as a DateSeparator. I almost always suggest to use DateTime.TryParseExact method in this kind of situations;
string s = "6/11/2014 9:00";
DateTime dt;
if(DateTime.TryParseExact(s, "d/MM/yyyy H:mm", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss"));
// result will be 2014-11-06 09:00:00
}
If you know formats of your dates, then you can do this:
string stringDate = "6/11/2014 9:00";
//Your date formats of input
string[] dateFormats = new string[]
{
"d/MM/yyyy H:mm",
"dd/MM/yyyy H:mm",
"dd/MM/yyyy HH:mm",
"dd/MM/yyyy H:mm:ss",
"dd/MM/yyyy HH:mm:ss"
/* And other formats */
};
DateTime convertedDate;
bool isSuccessful = DateTime.TryParseExact(stringDate, dateFormats,
System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out convertedDate);
if (isSuccessful)
{
//If conversion was successful then you can print your date at any format you like
//because you have your date as DateTime object
Console.WriteLine(convertedDate.ToString("dd-MM-yyyy HH:mm:ss")); /* Or other format you want to print */
}
I hope it will be helpful to you.

ASP.NET format string date

I am connecting to a database, executing a query, and putting the data in a list. I have strings that have dates like so mm/dd/yyyy hour:minute:second AM or PM I am looking to format this data into yyyy-mm-dd with no time.
This is where I am assigning the data:
airportItems.ContractReceived_F = dataReader.GetValue(1).ToString();
how would I convert the dataReader.GetValue(1).ToString(); to the date format I want?
I have tried the following:
airportItems.ContractReceived_F = string.Format("{0:d}", dataReader.GetValue(1).ToString());
I am defining ContractReceived_F as string:
public string ContractReceived_F { get; set; }
and it still returned the time.
Use this:
airportItems.ContractReceived_F = dataReader.GetDateTime(1).ToString("yyyy-MM-dd");
where yyyy represents the year, MM represents the month and dd represents the day.
why not parse the data you need to like this
DateTime unparsed_date = mydatevalue; //any date in any date format
string parsed_date = unparsed_date.toString("dd mm yyyy");
Theres an article on the different parses on msdn that i found for you
check it out
Credit goes to fubo for the link (thumbs up)
I suggest to use the TryParseExact
Then you choose the date format that you need
For example :
DateTime OutputDate = null;
DateTime.TryParseExact(DateFromTheView, "yyyy/MM/dd H:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out OutputDate);
In the example : the format is "yyyy/MM/dd H:mm:ss tt" and the input date string is DateFromTheView. The OutputDate will take as value the new datetime object and if the instruction fails it will take null.

Datetime format Issue: String was not recognized as a valid DateTime

I want to format the input string into MM/dd/yyyy hh:mm:ss format in C#.
The input string is in format MM/dd/yyyy hh:mm:ss
For example :"04/30/2013 23:00"
I tried Convert.ToDateTime() function, but it considers 4 as date and 3 as month which is not what I want. Actually month is 04 and date is 03.
I tried DateTime.ParseExact() function also, But getting Exception.
I am getting error:
String was not recognized as a valid DateTime.
Your date time string doesn't contains any seconds. You need to reflect that in your format (remove the :ss).
Also, you need to specify H instead of h if you are using 24 hour times:
DateTime.ParseExact("04/30/2013 23:00", "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture)
See here for more information:
Custom Date and Time Format Strings
You can use DateTime.ParseExact() method.
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified format and culture-specific
format information. The format of the string representation must match
the specified format exactly.
DateTime date = DateTime.ParseExact("04/30/2013 23:00",
"MM/dd/yyyy HH:mm",
CultureInfo.InvariantCulture);
Here is a DEMO.
hh is for 12-hour clock from 01 to 12, HH is for 24-hour clock from 00 to 23.
For more information, check Custom Date and Time Format Strings
try this:
string strTime = "04/30/2013 23:00";
DateTime dtTime;
if(DateTime.TryParseExact(strTime, "MM/dd/yyyy HH:mm",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out dtTime))
{
Console.WriteLine(dtTime);
}
This can also be the problem if your string is 6/15/2019. DateTime Parse expects it to be 06/15/2019.
So first split it by slash
var dateParts = "6/15/2019"
var month = dateParts[0].PadLeft(2, '0');
var day = dateParts[1].PadLeft(2, '0');
var year = dateParts[2]
var properFormat = month + "/" +day +"/" + year;
Now you can use DateTime.Parse(properFormat, "MM/dd/yyyy"). It is very strange but this is only thing working for me.
change the culture and try out like this might work for you
string[] formats= { "MM/dd/yyyy HH:mm" }
var dateTime = DateTime.ParseExact("04/30/2013 23:00",
formats, new CultureInfo("en-US"), DateTimeStyles.None);
Check for details : DateTime.ParseExact Method (String, String[], IFormatProvider, DateTimeStyles)
DateTime dt1 = DateTime.ParseExact([YourDate], "dd-MM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
Note the use of HH (24-hour clock) rather than hh (12-hour clock), and the use of InvariantCulture because some cultures use separators other than slash.
For example, if the culture is de-DE, the format "dd/MM/yyyy" would expect period as a separator (31.01.2011).
Below code worked for me:
string _stDate = Convert.ToDateTime(DateTime.Today.AddMonths(-12)).ToString("MM/dd/yyyy");
String format ="MM/dd/yyyy";
IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);
DateTime _Startdate = DateTime.ParseExact(_stDate, format, culture);
You may use this type format (get formatted data from sql server)
FORMAT(convert(datetime,'16/04/2018 10:52:20',103),'dd/MM/yyyy HH:mm:ss', 'en-us')
CONVERT(VARCHAR,convert(datetime,'16/04/2018 10:52:20',103), 120)

String to dateTime in C#?

How Can I convert following date string to dateTime:
Fri, 18 Dec 2009 9:38 am PST
I tried DateTime.Parse(string)
I got following error:
The string was not recognized as a valid DateTime. There is an unknown word starting at index 25. System.SystemException {System.FormatException}
UPDATE
I tried to get weather from yahoo and I tried to get date like this:
Date = DateTime.Parse(feed.Element(yWeatherNS + "condition").Attribute("date").Value),
I debugged it. date attribute is correct (like above).
Thanks.
I don't think there's anything in the BCL which will parse time zone abbreviations. (They should be avoided where possible anyway, as they can be ambiguous.)
If you don't mind losing the time zone information, you can use something like this:
using System;
using System.Globalization;
static class Test
{
static void Main()
{
string text = "Fri, 18 Dec 2009 9:38 am PST";
DateTime parsed = TrimZoneAndParse(text);
Console.WriteLine(parsed);
}
static DateTime TrimZoneAndParse(string text)
{
int lastSpace = text.LastIndexOf(' ');
if (lastSpace != -1)
{
text = text.Substring(0, lastSpace);
}
return DateTime.ParseExact(text,
"ddd, dd MMM yyyy h:mm tt",
CultureInfo.InvariantCulture);
}
}
Note that that assumes a fixed date/time format and culture. Your needs may vary, and you should also consider using TryParse or TryParseExact if this is user input.
If DateTime.Parse can't figure it out automatically, you can use DateTime.ParseExact where you specify the format being used.
In your case this would be something like, you'll need to replace the 'PST' yourself however:
CultureInfo provider = CultureInfo.InvariantCulture;
string dateString = "Fri, 18 Dec 2009 9:38 am PST";
dateString = dateString.Replace("PST", "-08:00");
string format = "ddd, dd MMM yyyy h:mm tt zzz";
DateTime result = DateTime.ParseExact(dateString, format, provider);
If your program needs to work with different timezone abbrevations, you'll have to build a Dictionary with abbrevation to time zone offset conversions.

Categories