String to dateTime in C#? - 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.

Related

How to convert datetime format in 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_

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");

Convert 1st day string to Datetime

I'm looking for a way to be able to convert a date string like this:
"1st Oct 2018" => 2018-10-01
Or this:
"10th Mar 2015" => 2015-03-10
To it's equivalent string in the format yyyy mm dd. I have tried the following code, but no luck:
DateTime dt = DateTime.ParseExact(stringDate, "yyyy mm dd", CultureInfo.InvariantCulture);
Just in addition to great answer from Daisy:
[TestCase("15th Oct 2018")]
[TestCase("1st Oct 2018")]
[TestCase("2nd Oct 2018")]
[TestCase("3rd Oct 2018")]
[TestCase("3d Oct 2018")]
public void Action(string dateStr)
{
// Act
var dt = DateTime.ParseExact(Regex.Replace(dateStr, "(th|st|nd|rd|d)", ""), "d MMM yyyy", CultureInfo.CurrentCulture);
//Assert
Console.WriteLine(dt);
}
UPD: added great suggestions from Dmitry Bychenko.
A DateTime value doesn't have a format - it's just a value. (Just like an int isn't inherently decimal or hex - you choose how to format it when you convert it to a string, and the default is to use decimal.)
The string you're passing into DateTime.ParseExact is the expected input format - and your strings don't have the format "yyyy mm dd". (Note that in date/time format strings, "mm" means minutes, so you'd want "MM" instead of "mm" anyway... but that won't help here.)
Your date format is nearly "d MMM yyyy" (day, short month name, year) using English month names - but the problem is the ordinal part ("st", "nd", "th"). As far as I know there's no simple way of handling that with DateTime.ParseExact. Instead, I'd probably use a regular expression or simple string replacement to remove the ordinal part, so that you do have a string in the format "d MMM yyyy" and then parse that.
For the string replacement part, the answers to this question are appropriate. So here's a complete example using your sample data:
using System;
using System.Globalization;
class Test
{
static void Main()
{
Console.WriteLine(ParseWithOrdinals("10th Mar 2015"));
Console.WriteLine(ParseWithOrdinals("1st Oct 2018"));
}
private static DateTime ParseWithOrdinals(string input) =>
DateTime.ParseExact(
RemoveOrdinals(input), // Text to parse
"d MMM yyyy", // Format of text
CultureInfo.InvariantCulture); // Expect English month names, Gregorian calendar
// From https://stackoverflow.com/questions/17710561
private static string RemoveOrdinals(string input) =>
input
.Replace("0th", "0")
.Replace("1st", "1")
.Replace("2nd", "2")
.Replace("3rd", "3")
.Replace("11th", "11") // Need to handle these separately...
.Replace("12th", "12")
.Replace("13th", "13")
.Replace("4th", "4")
.Replace("5th", "5")
.Replace("6th", "6")
.Replace("7th", "7")
.Replace("8th", "8")
.Replace("9th", "9");
}
(Note that I haven't formatted the result as yyyy-MM-dd in the output, so you'll get your local date/time format.)
There is also a native approach without string remove / replace / Regex
If you know the characters, you can escape them with the ' character inside the date pattern. So "15th Oct 2018" works for this pattern "d'th' MMM yyyy"
Now there are "st","nd","rd","th" so you can try each of them and chose the working one.
Into the overload of TryParseExact(String, String[], IFormatProvider, DateTimeStyles, DateTime) you can pass a range of allowable formats.
string input = "15th Oct 2018";
DateTime result = DateTime.Now;
string[] patterns = { "d'st' MMM yyyy", "d'nd' MMM yyyy", "d'rd' MMM yyyy", "d'th' MMM yyyy"};
bool success = DateTime.TryParseExact(input, patterns, CultureInfo.InvariantCulture, DateTimeStyles.None, out result);
if (success)
Console.WriteLine(result.ToString("yyyy-MM-dd"));
https://dotnetfiddle.net/H8ulyo

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)

c# Parsing UTC datetime

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

Categories