C# format string to DateTime - c#

I read a datetime from text file with this format
Thu Apr 16 09:55:44 2015
How can I format this like 16/04/2015 09:55:44 ?

Do it in two steps. Use DateTime.ParseExact to parse the original string, then use ToString() to output it in the other desired format:
var input = "Thu Apr 16 09:55:44 2015";
var parsed =
DateTime.ParseExact(input, "ddd MMM dd HH:mm:ss yyyy", CultureInfo.InvariantCulture);
var output = parsed.ToString("dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

First of all you need to convert to DateTime:
https://msdn.microsoft.com/en-us/library/cc165448.aspx
Then you need to convert to String again, using the correctly format, as you can see here:
https://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx
// This example displays the following output to the console:
// d: 6/15/2008
// D: Sunday, June 15, 2008
// f: Sunday, June 15, 2008 9:15 PM
// F: Sunday, June 15, 2008 9:15:07 PM
// g: 6/15/2008 9:15 PM
// G: 6/15/2008 9:15:07 PM
// m: June 15
// o: 2008-06-15T21:15:07.0000000
// R: Sun, 15 Jun 2008 21:15:07 GMT
// s: 2008-06-15T21:15:07
// t: 9:15 PM
// T: 9:15:07 PM
// u: 2008-06-15 21:15:07Z
// U: Monday, June 16, 2008 4:15:07 AM
// y: June, 2008
//
// 'h:mm:ss.ff t': 9:15:07.00 P
// 'd MMM yyyy': 15 Jun 2008
// 'HH:mm:ss.f': 21:15:07.0
// 'dd MMM HH:mm:ss': 15 Jun 21:15:07
// '\Mon\t\h\: M': Month: 6
// 'HH:mm:ss.ffffzzz': 21:15:07.0000-07:00

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.

Unable to parse abbreviated day name from string

I'm trying to parse a date in my string using DateTime.TryParseExact. The string looks like this:
Wed, 21 Apr 2019 07:28:45 GMT
However, the parse function always fails when I use the ddd format specifier. If I remove 'Wed' from the string and the 'ddd' part from the format string, it parses just fine.
Here's a bit of code that reproduces the problem
var ci = CultureInfo.CreateSpecificCulture("en-GB");
var datesToParse = new[] { "Wed, 21 Apr 2019 07:28:45 GMT", "21 Apr 2019 07:28:45 GMT" };
var formats = new[] { "ddd, dd MMM yyyy HH:mm:ss 'GMT'", "dd MMM yyyy HH:mm:ss 'GMT'" };
foreach (var dateToParse in datesToParse)
{
var result = DateTime.TryParseExact(dateToParse, formats, ci, DateTimeStyles.AllowWhiteSpaces, out DateTime parsedDate)
? parsedDate.ToLongDateString()
: $"Unable to parse date: {dateToParse}";
Console.WriteLine(result);
}
Console.ReadLine();
And the output:
Unable to parse date: Wed, 21 Apr 2019 07:28:45 GMT
21 April 2019
I'm not really sure what I'm doing wrong here. Any help would be appreciated.
edit: improved the output and program syntax
Your issue is that 21 April 2019 was a Sunday and not a Wednesday. This works fine "Sun, 21 Apr 2019 07:28:45 GMT"

How to Parse a Date Time with TimeZone Info

I have following string ,
Thu Sep 24 2015 00:00:00 GMT+0530 (IST)
I tried with following but it's faling.
var twDate = DateTime.Parse("Thu Sep 24 2015 00:00:00 GMT+0530 (IST) ");
Can not use replace , as IST wont be fixed. Any Ideas?
You need to trim the time zone abbreviation off using normal string operations, then specify a custom date and time format string. For example:
// After trimming
string text = "Thu Sep 24 2015 00:00:00 GMT+0530";
var dto = DateTimeOffset.ParseExact(
text,
"ddd MMM d yyyy HH:mm:ss 'GMT'zzz",
CultureInfo.InvariantCulture);
Console.WriteLine(dto);
Note the use of CultureInfo.InvariantCulture here - you almost certainly don't want to parse using the current thread's current culture.
If your string always has the same format and length, you could use this to get UTC:
String dtstr = "Thu Sep 24 2015 00:00:00 GMT+0530 (IST)";
int zoneMin = int.Parse(dtstr.Substring(29, 2)) * 60 + int.Parse(dtstr.Substring(31, 2));
if (dtstr.Substring(28, 1) == "+") zoneMin = -zoneMin;
DateTime dt = DateTime.Parse(dtstr.Substring(0, 24)).AddMinutes(zoneMin);

Casting String to DateTime

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)

Date format - Excel and C#

My C# application send a formatted date (ex: 9/6/2010 - dd/mm/yyyy) to an excel spreadsheet... but then... it comes to 6/9/2010! (mm/dd/yyyy)
I just use the following code to send the date:
VarRowColumnWhatever = _MyList.MyObject.MyDateTime.Date.ToString();
Debbuging it, i can see that the value are correct! But not in the spreadsheet =(
I began to think that is something to do with Excel...
Someone please can help me? Thanks!
Stick a string according to the pattern you want into the ToString() portion.
For instance, to get the Full Day, Month, Date, Year, i'd put:
_MyList.MyObject.MyDateTime.TimeOfDay.ToString("D");
which would output the string: "Wednesday, June 23, 2010"
// This example displays the following output to the console:
// d: 6/15/2008
// D: Sunday, June 15, 2008
// f: Sunday, June 15, 2008 9:15 PM
// F: Sunday, June 15, 2008 9:15:07 PM
// g: 6/15/2008 9:15 PM
// G: 6/15/2008 9:15:07 PM
// m: June 15
// o: 2008-06-15T21:15:07.0000000
// R: Sun, 15 Jun 2008 21:15:07 GMT
// s: 2008-06-15T21:15:07
// t: 9:15 PM
// T: 9:15:07 PM
// u: 2008-06-15 21:15:07Z
// U: Monday, June 16, 2008 4:15:07 AM
// y: June, 2008
//
// 'h:mm:ss.ff t': 9:15:07.00 P
// 'd MMM yyyy': 15 Jun 2008
// 'HH:mm:ss.f': 21:15:07.0
// 'dd MMM HH:mm:ss': 15 Jun 21:15:07
// '\Mon\t\h: M': Month: 6
// 'HH:mm:ss.ffffzzz': 21:15:07.0000-07:00
Try to write your code like this:
VarRowColumnWhatever = _MyList.MyObject.MyDateTime.Date.ToString("dd\/MM\/yyyy");
or make sure your culture is set to one with your desired format.
If the Excel cell you are putting the value into is of Date type in Excel (if using interop), then you should use:
VarRowColumnWhatever = _MyList.MyObject.MyDateTime.Date.ToOADate();

Categories

Resources