How to convert datetime format in c#? - c#

I want to convert the DateTime format using c#. This is my code
string date = "Thu May 20 2021 00:00:00 GMT-0700 (Pacific Daylight Time)";
var s = DateTime.ParseExact(date, "dd-MM-yyyy HH:mm:ss", null);
But this code not working the exception is 'System.FormatException: 'String was not recognized as a valid DateTime.'

The format you provide must match with the format used in the string. Hence the name ParseExact. After playing around a bit I was able to match these:
string date = "Thu May 20 2021 00:00:00 GMT-0700"
var s = DateTime.ParseExact(date, "ddd MMM dd yyyy HH:mm:ss \"GMT\"zzz", null);
You may need to manually truncate the (Pacific Daylight Time) or include it in the format as a literal (like I did with GMT here).
For more information you can work with DateTime format specifiers

Your format string means that the date value must be something like that:
string date = "20-05-2021 12:00:00";
var s = DateTime.ParseExact(date, "dd-MM-yyyy HH:mm:ss", null);
Try to use an other date value or change the date format string.
You can find a lot of good examples here:
https://learn.microsoft.com/en-us/dotnet/api/system.datetime.parseexact?view=net-5.0#System_DateTime_ParseExact_System_String_System_String_System_IFormatProvider_

Related

How to Convert a datetime to Long Date?

Below is my code,
DateTime DateFrom_ = Convert.ToDateTime(CSO.dateFrom);
I am getting the value currently like - 29/10/2019 00:00:00
what i want is I want to convert above to this format - Tue, 29 Oct 2019
can anyone please guide me how to do this, Thank you.
Below one worked for me,
DateTime DateFrom_ = Convert.ToDateTime(CSO.dateFrom);
var convertedDate = DateFrom_.ToString("ddd', 'dd' 'MMM' 'yyyy");
You can do it easily, using DateTime.ParseExact to parse from certain format, and then use ToString with different format to represent it based on your need:
var date = DateTime.ParseExact("29/10/2019 00:00:00", "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
date.ToString("ddd, dd MMM yyyy"); // output Tue, 29 Oct 2019
Please note, if you need culture specific long date representation, then you should use ToString("D", cultureInfo) overload. That way, your format will be aligned with the culture defined format.
I think using DateTime.ToString() with the specific format should do the work. Try this one:
date.ToString("D", CultureInfo.CreateSpecificCulture("en-US"));
As it's been mentioned in here, you want to be using "DateTime.ParseExact"
var str = "Tue, 29 Oct 2019";
var date = DateTime.ParseExact(str, "ddd, dd MMM yyyy", CultureInfo.InvariantCulture);
You may split the date and use DateTime.ParseExact.
string[] tokens = "29/10/2019 00:00:00".Split(' ');
DateTime DateFrom_ = DateTime.ParseExact(tokens[0], "dd/MM/yyyy", CultureInfo.InvariantCulture);
var dateString = DateFrom_.ToString("ddd, dd MMM yyyy");

Parse RSS pubdate to DateTime

I get this date string from an RSS:
Wed, 16 Dec 2015 17:57:15 +0100
I need to parse into a DateTime. Ive googled and searched stack overflow and gotten to the following answer (ive tried with only one, two and four 'z' instead of three)
string parseFormat = "ddd, dd MMM yyyy HH:mm:ss zzz";
DateTime date = DateTime.ParseExact(dateString, parseFormat,
DateTimeFormatInfo.CurrentInfo,
DateTimeStyles.None);
But I get this error:
System.FormatException: String was not recognized as a valid
DateTime.
Change your code to
string parseFormat = "ddd, dd MMM yyyy HH:mm:ss zzz";
DateTime date = DateTime.ParseExact(dateString, parseFormat,
CultureInfo.InvariantCulture);
Hope it helps!
As commented, your format and string matches unless if your CurrentCulture is english-based one. If it is not, it can't parse these Wed and Dec parts successfully.
On the other hand, zzz format specifier does not recommended for DateTime parsing.
From documentation;
With DateTime values, the "zzz" custom format specifier represents the
signed offset of the local operating system's time zone from UTC,
measured in hours and minutes. It does not reflect the value of an
instance's DateTime.Kind property. For this reason, the "zzz" format
specifier is not recommended for use with DateTime values.
However, I would parse it to DateTimeOffset instead of DateTime since you have an UTC Offset in your string like;
var dateString = "Wed, 16 Dec 2015 17:57:15 +0100";
string parseFormat = "ddd, dd MMM yyyy HH:mm:ss zzz";
DateTimeOffset dto = DateTimeOffset.ParseExact(dateString, parseFormat,
CultureInfo.InvariantCulture,
DateTimeStyles.None);
Now, you have a DateTimeOffset as {16.12.2015 17:57:15 +01:00} which as +01:00 Offset part.

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.

Can this date be converted automatically?

I know that C# has some great date conversion tools. What I'm I'm wondering is if I can automatically convert this string to a date object:
"Fri May 11 00:00:00 EDT 2012"
I'm thinking I'll have to manually parse the month, day, and year but I'm hoping there is an easier way built-in. Any help would be appreciated.
Thanks!
You can use DateTime.ParseExact or DateTime.TryPraseExact to provide a custom format:
DateTime result;
if (!DateTime.TryParseExact(
"Fri May 11 00:00:00 EDT 2012",
"ddd MMM dd HH:mm:ss EDT yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out result)) {
// handle invalid date
}
All of the format options are listed on the Custom Date and Time Format Strings page on MSDN.
Convert.ToDateTime("Fri May 11 00:00:00 EDT 2012") should work just fine.
http://msdn.microsoft.com/en-us/library/xhz1w05e.aspx
Take a look at that. Should help you out.
Example:
// Convert a string returned by DateTime.ToString("R").
String dateString = "Sat, 10 May 2008 14:32:17 GMT";
ConvertToDateTime(dateString);
Yes, you can parse the string into a DateTime object :
String format = "ddd MMM dd hh:mm:ss EDT yyyy";
String dateString = "Fri May 11 00:00:00 EDT 2012";
DateTime result = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);

How to convert 31/03/2011 00:00:00 date format to 31 Mar 2011 in C#

I have got below date format in my result,I am using C# 2.0
ExpiryDate = "31/03/2011 00:00:00";
spnExpiryDate.InnerHtml = ExpiryDate;
Now when I am going to show this in HTML it should be converted to 31 Mar 2011 format.
Please suggest!
First, parse the string to a DateTime, and then format it using the DateTime's ToString:
DateTime myDateTime = DateTime.Parse( "31/03/2011 00:00:00" );
spnExpiryDate.InnerHtml = myDateTime.ToString("dd MMM yyyy");
This should do it:
var culture = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB");
spnExpiryDate.InnerHtml = DateTime.Parse(ExpiryDate, culture).ToString("d MMM yyyy");
You can leave out the culture bits if your server's default culture is already dd/mm/yyyy.
First parse date then format how you need:
DateTime dt = DateTime.Parse("31/03/2011 00:00:00");
.InnerHtml = String.Format("{0:dd MMM yyyy}", dt);
There is good link that i use almost everytime when i need format date.
Also check this aswer about extention method for datetime formatting.
at first parse your string to DateTime
var date = DateTime.Parse("31/03/2011 00:00:00", "dd/mm/yyyy HH:mm:ss");
then user method "ToString"
date.ToString("dd MMM yyyy")
You didn't say how you are outputting it, but basically you want to provide the format when you call the ToString:
aTextBox.Text = myDate.ToString("dd MMMM yyyy");
The another way is
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Month);
gives you Month Name

Categories