Casting String to DateTime - c#

I have a string in format
Jul 13 2011 1:07PM
I want to cast it as
dd/MM/yyyy HH:mm tt
e.g: 13/7/2011 11:49:00 AM //string=Jul 13 2011 1:07PM
I am using following code to cast it to date.
DateTime date = Convert.ToDateTime(Convert.ToDateTime(myDateString).ToString("dd/MM/yyyy HH:mm:ss"));
This works fine if my day in my string is less than 13
Jul 12 2011 1:07PM //this will cast to desire format fine!
Jul 13 2011 1:07PM //gives error String was not recognized as a valid DateTime.
I understand that it is taking day as month but I can not found a way to cast it to desire format.

See DateTime.ParseExact :
DateTime date = DateTime.ParseExact(myDateString, "MMM dd YYYY H:mmtt", CultureInfo.InvariantCulture);
See also Time Format Strings

You should use DateTime.TryParse
DateTime dt ;
if (DateTime.TryParse("Jul 13 2011 1:07PM",out dt))
MessageBox.Show("Converted to Date object");
Post that you use the ToString() method to get the desired output
dt.ToString("dd/MM/yyyy HH:mm")

First, convert the string Jul 13 2011 1:07PM to a date:
var date = Convert.ToDateTime("Jul 13 2011 1:07PM");
Then, convert it to a string in the format you like:
var dateText = date.ToString("dd/MM/yyyy HH:mm:ss");

I believe you're searching for this:
Date.ParseExact("Jul 13 2011 1:07PM", "MMM d yyyy h:mmtt", Globalization.CultureInfo.InvariantCulture)

Related

Convert string to string(datetime) in EST

I have string in "Mon, 20 Mar 2021 14:04:48 +0000"
and I want to convert it as "20 Mar 2021 | 14:04 PM"
I want to convert the string as it is but it was appearing differently in my local and server.
First of all 20 Mar 2021 is Saturday, not Monday, let's correct it. Then you can ParseExact to get DateTime and finally represent it in the required format with a help of ToString():
string source = "Sat, 20 Mar 2021 14:04:48 +0000";
string result = DateTime
.ParseExact(source, "ddd, dd MMM yyyy HH:mm:ss zzz", CultureInfo.InvariantCulture)
.ToUniversalTime()
.ToString("dd MMM yyyy' | 'HH:mm tt", CultureInfo.InvariantCulture);
Notes:
It seems that you want to obtain Universal (not Local) time, that's why I've added ToUniversalTime()
14:04 PM looks strange for me (14:04 and 02:04 PM are much more frequent formats); put hh instead of HH to have 02:04 PM
If you actually want to be manipulating the timezone information, then use Noda Time.
If that's your exact text format, and the dates and times are what you want, you can convert it manually:
var input = "Mon, 20 Mar 2021 14:04:48 +0000";
var dateParts = input.Split(' ');
var timeParts = dateParts[4].Split(':');
var amPm = int.Parse(timeParts[0]) < 12 ? "AM" : "PM";
var output = $"{dateParts[1]} {dateParts[2]} {dateParts[3]} | {timeParts[0]}:{timeParts[1]} {amPm}";
System.Console.WriteLine(output); // "20 Mar 2021 | 14:04 PM"
Or, if you are feel adventurous, use a regular expression.

How to Convert long string to DateTime?

I have a date string in the following format:
var dateString = Fri Jun 26 2020 00:00:00 GMT+0100 (British Summer Time)
How can I convert this to a DateTime in C# such as 26/06/2020 00:00:00
I have tried:
DateTime.Parse(dateString);
And:
DateTime.ParseExact(dateString);
And I get:
System.FormatException: 'String was not recognized as a valid DateTime.'
You can accomplish this by using DateTime.ParseExact and providing a custom date time format. However, this will only work if you first modify the input string to be able to fit the custom date and time format strings that are included in .net.
CultureInfo provider = CultureInfo.InvariantCulture;
var input = "Fri Jun 26 2020 00:00:00 GMT+0100 (British Summer Time)";
// set up a regex that will match the text starting with GMT, and extract just the timezone offset
// (the description of the timezone is irrelevant here)
var r = new Regex(#"GMT([+-]\d\d\d\d) \([\w\s]*\)");
// this will remove the extra text: "Fri Jun 26 2020 00:00:00 +0100"
// now we can match it in our format string
var s = r.Replace(input, "$1");
var f = "ddd MMM dd yyyy hh:mm:ss zzz"; // matches the s variable
var d = DateTime.ParseExact(s, f, provider); // you now have parsed your date
This will include the timezone offset in the DateTime object. If you just want it to be set to "26/06/2020 00:00:00" and to ignore the datetime offset, then just change the regex replace above to replace with String.Empty instead of $1.
This will solve your problem.
var dateString = "Fri Jun 26 2020 00:00:00 GMT + 0100(British Summer Time)"; Console.WriteLine(DateTime.Parse(dateString.Substring(4, 11)));
Hello so what you can do is you can take advantage of "datetime" class and just write this:
DateTime.Now.ToString("MM/dd/yyyy HH:mm");
edit: sorry i forgot to supply the link haha
https://www.c-sharpcorner.com/blogs/date-and-time-format-in-c-sharp-programming1

On converting a string to a DateTime object

Am unable to convert a string which represents date and time ex: "Tue Mar 18 14:37:34 PDT 2014" to a DateTime object. From the format I can figure it out to be in the RFC 1123 format. What is the best way to parse date strings as above?
Timezone literals are not supported by DateTime.Parse/ParseExact. Here is a workaround:
string inputDate = "Tue Mar 18 14:37:34 PDT 2014";
inputDate = inputDate.Replace("PDT", "-7");
DateTime d = DateTime.ParseExact(inputDate, "ddd MMM dd HH:mm:ss z yyyy", culture);
Console.WriteLine(d);
If you can make the format of the string like this (you are pretty close):
Sat, 01 Nov 2008 19:35:00 GMT
You can use DateTime.Parse(dateString);
Find more information here http://msdn.microsoft.com/en-us/library/vstudio/1k1skd40(v=vs.100).aspx

Error : String was not recognized as a valid DateTime while converting to date format in c#

Here is the date time format i'm trying to format.I'm getting this date format from twitter apis
string date = "Thu Jul 18 17:39:53 +0000 2013"
i tried
Convert.ToDateTime(date).ToString("dd/MM/yyyy")
But it says String was not recognized as a valid DateTime.
This works:
DateTime.ParseExact(dtStr, "ddd MMM dd HH:mm:ss zzzz yyyy", CultureInfo.InvariantCulture)
ParseExact and TryParseExact allows to use a custom format string. ddd is the abbreviated day name, MMM the abbreviated month name, dd the day number, HH hours in 24h clock format, mm minutes, ss seconds, zzzz the time-zone and yyyy the years.
I have used CultureInfo.InvariantCulture to specify that the current culture is not used but InvariantCulture which is similar to "en-US".
Demo
works but after getting date from your line of code i tried to do
date.ToString("dd/mm/yyyy") but get the string as 12-12-2013, no
slashes
/ is a replacement character for your current culture's date-separator which is obviously -. So also use CultureInfo.InvariantCulture to specify that the separator should be used without using your current culture:
string result = dateTime.ToString("dd/mm/yyyy", CultureInfo.InvariantCulture);
See: The "/" Custom Format Specifier
Try this
DateTime.ParseExact(YourDate, "ddd MMM dd HH:mm:ss KKKK yyyy", CultureInfo.InvariantCulture)
Its better to use Invariant culture than Current culture
You are trying to convert a non-standard format, so use this:
string dateStr = "Thu Jul 18 17:39:53 +0000 2013";
DateTime date = DateTime.ParseExact(dateStr, "ddd MMM dd h:mm:ss KKKK yyyy", System.Globalization.CultureInfo.InvariantCulture);
Or build the correct format for your input.
How about like;
string date = "Thu Jul 18 17:39:53 +0000 2013";
DateTime dt = DateTime.ParseExact(date, "ddd MMM dd HH:mm:ss KKKK yyyy", CultureInfo.InvariantCulture);
Console.WriteLine(dt);
Output will be;
18.07.2013 20:39:53
K for time zone information in here.
Check out for more information;
Custom Date and Time Format Strings
Your date string needs to be this:
Thu Jul 18 2013 17:39:53 +0000
Whatever is producing your string needs to have the year value after the month and day and before the time, like above.
string date = "Thu Jul 18 2013 17:39:53 +0000";
var theDate = Convert.ToDateTime(date);
Note: This will produce a valid .NET DateTime object.
UPDATE:
If you cannot change the string produced, then use the ParseExact method with a custom format, like this:
string date = "Thu Jul 18 17:39:53 +0000 2013";
var theDate = DateTime.ParseExact(date, "ddd MMM dd H:mm:ss zzz yyyy", CultureInfo.InvariantCulture);
Try using DateTime.ParseExact.
string date = "Thu Jul 18 17:39:53 +0000 2013"
DateTime date = DateTime.ParseExact(date, "dd/MM/yyyy", null);
this.Text="22/11/2009";
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);

JSON date from tweeter to C# format

How to format a JSON date obtained from twitter to a C# DateTime ?
Here is the format of the date I receive :
"Tue, 19 Feb 2013 13:06:17 +0000"
Can I do it with JSON.NET ?
Solved with use of DateTime.ParseExact
-> http://blog.kevinyu.org/2012/07/handling-json-in-net.html
Link Update: the linked blog post is offline. It cached copy can still be referenced via the Way Back Machine Internet Archive.
The common .NET code copied from the blog post is:
public const string Const_TwitterDateTemplate = "ddd MMM dd HH:mm:ss +ffff yyyy";
DateTime createdAt = DateTime.ParseExact((string)jo["created_at"],
Const_TwitterDateTemplate, new System.Globalization.CultureInfo("en-US"));
where
variable jo is a JSON object representing the created_at date property, but effectively the Twitter date string goes into this parameter
Part of code from flow's answer.
public const string Const_TwitterDateTemplate = "ddd MMM dd HH:mm:ss +ffff yyyy";
DateTime createdAt = DateTime.ParseExact((string)jo["created_at"], Const_TwitterDateTemplate, new System.Globalization.CultureInfo("en-US"));
The answers above that use the ffff format specifier seem to return the correct result, but technically this is wrong. ffff is the format specifier for ten thousandths of a second, and the +0000 in a Twitter date indicates the hours and minutes offset from UTC. See the format below:
string twitterTime = "Wed Feb 22 15:49:01 +0000 2017";
string twitterTimeformat = "ddd MMM dd HH:mm:ss zzz yyyy";
DateTime dateTime = DateTime.ParseExact(twitterTime, twitterTimeformat,
CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
Console.WriteLine(dateTime);
Result: 2/22/2017 3:49:01 PM
You can edit the DateTimeStyles enumeration to return the local time instead of UTC if desired.
Custom Date and Time Format Strings
DateTimeStyles Enumeration
It's DateTimeOffset not DateTime. Following should work.
DateTimeOffset parsed = DateTimeOffset.Parse("Tue, 19 Feb 2013 13:06:17 +0000");
I needed a PowerShell variant of these answers and the following worked for me.
PS> $Created_At = 'Fri Jun 05 18:15:48 +0000 2020'
PS> [datetime]::ParseExact($Created_At,'ddd MMM dd HH:mm:ss zzz yyyy',(Get-Culture))
Friday, June 5, 2020 1:15:48 PM

Categories

Resources