How to format string to datetime? - c#

I have devexpress dateedit object and I send selected date to controller from clientside but i cant convert my string date value to datetime value
When I try I get this error => string was not recognized as a valid DateTime
my string date value => Thu Aug 28 2014 00:00:00 GMT+0300 (Turkey Daylight Time)
Convert Code =>
DateTime startDate = DateTime.ParseExact(sDate, "ddd MMM d yyyy HH:mm:ss zzzz", CultureInfo.InvariantCulture);
How should I do format this string ?

You need to "escape" unrecognized symbols with single quote:
var sDate = "Thu Aug 28 2014 00:00:00 GMT+0300 (Turkey Daylight Time)";
var format = "ddd MMM dd yyyy HH:mm:ss 'GMT'zzzz '(Turkey Daylight Time)'";
DateTime startDate = DateTime.ParseExact(sDate, format, CultureInfo.InvariantCulture);
Console.WriteLine(startDate);
prints:
8/28/2014 12:00:00 AM
Works well with single d in third group, added one just for clarity.
Single or double quotes denote Literal string delimiter. You can read and check more examples at this msdn article on DateTime formats

First convert date string to date and then date to ISO and send it to server. That would work.
var date = new Date("Thu Aug 28 2014 00:00:00 GMT+0300")
var sDate = date.toISOString();

Try removing the unknown format with Regex first.
var sDate = #"Thu Aug 28 2014 00:00:00 GMT+0300 (Turkey Daylight Time)";
var sDateOnly = Regex.Replace(sDate, #"\s*(\(.*\))", m => string.Empty);
var f = #"ddd MMM d yyyy HH:mm:ss \G\M\Tzzzz";
DateTime startDate = DateTime.ParseExact(sDateOnly, f, CultureInfo.InvariantCulture);

Related

What's the format date Node js (new date()) on C# [duplicate]

I have date object in JavaScript which give me: "Wed Oct 01 2014 00:00:00 GMT+0200";
I try to parse it but I get an exception:
string Date = "Wed Oct 01 2014 00:00:00 GMT+0200";
DateTiem d = DateTime.ParseExact(Date,
"ddd MM dd yyyy HH:mm:ss GMTzzzzz",
CultureInfo.InvariantCulture);
MM format specifier is 2 digit month number from 01 to 12.
You need to use MMM format specifier instead for abbreviated name of month.
And for your +0200 part, you need to use K format specifier which has time zone information instead of zzzzz.
And you need to use single quotes for your GMT part as 'GMT' to specify it as literal string delimiter.
string s = "Wed Oct 01 2014 00:00:00 GMT+0200";
DateTime dt;
if(DateTime.TryParseExact(s, "ddd MMM dd yyyy HH:mm:ss 'GMT'K",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
Console.WriteLine(dt);
}
Any z format specifier is not recommended with DateTime parsing. Because they represents signed offset of local time zone UTC value and this specifier doesn't effect DateTime.Kind property. And DateTime doesn't keep any offset value.
That's why this specifier fits with DateTimeOffset parsing instead.

Convert DateTime Format to Tuesday, 03 May 2016

In my asp.net page i want to display date in this format Tuesday, 03 May 2016 but when i retrieve data from sql server its showing 3/05/2016 12:00:00 AM
How to convert 3/05/2016 12:00:00 AM - to - Tuesday, 03 May 2016 in C# Code Behind File
Actually this is my code :
string strAccountCreatedDate = ds.Table[0].Rows[0]["AccountCreatedDate"].ToString();
strAccountCreatedDate = 3/05/2016 12:00:00 AM
Now i want to Convert strAccountCreatedDate Format to Tuesday, 03 May 2016 in through C# Coding
Try this
DateTime dt = DateTime.ParseExact("03/05/2016 12:00:00 AM", "dd/MM/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
string newdate = dt.ToString("dddd, dd MMM yyyy");
Console.WriteLine(newdate);
You should go through this link for conversion in any date format
DateTime dt = DateTime.Now;
string date = String.Format("{0:dddd,dd MMM yyyy}", dt);
Response.Write(date);
Try this :-
string strAccountCreatedDate = ds.Table[0].Rows[0]["AccountCreatedDate"].ToString();
DateTime dt = Convert.ToDateTime(strAccountCreatedDate);
string Formatteddate = dt.ToString("dddd, dd MMM yyyy");

How to parse string which contains GMT to DateTime?

How can I convert this string:
string aa ="Thu Jul 02 2015 00:00:00 GMT+0100 (GMT Standard Time)";
into a DateTime.
I tried to use the Convert.ToDateTime(aa); but didn't work
Thanks.
EDIT: error message - The string was not recognized as a valid DateTime
You can use DateTime.TryParseExact with the correct format string:
string dtString = "Thu Jul 02 2015 00:00:00 GMT+0100";
string format = "ddd MMM dd yyyy HH:mm:ss 'GMT'K";
DateTime date;
bool validFormat = DateTime.TryParseExact(dtString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
Console.Write(validFormat ? date.ToString() : "Not a valid format");
If the string contains (GMT Standard Time) at the end you could simply remove it first:
dtString = dtString.Replace("(GMT Standard Time)", "").Trim();
or use this format pattern:
string format = "ddd MMM dd yyyy HH:mm:ss 'GMT'K '(GMT Standard Time)'";
Further informations: https://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Using DateTime.Parse Method:
using System;
public class Example
{
public static void Main()
{
string[] dateStrings = {"2008-05-01T07:34:42-5:00",
"2008-05-01 7:34:42Z",
"Thu, 01 May 2008 07:34:42 GMT"};
foreach (string dateString in dateStrings)
{
DateTime convertedDate = DateTime.Parse(dateString);
Console.WriteLine("Converted {0} to {1} time {2}",
dateString,
convertedDate.Kind.ToString(),
convertedDate);
}
}
}
// These calls to the DateTime.Parse method display the following output:
// Converted 2008-05-01T07:34:42-5:00 to Local time 5/1/2008 5:34:42 AM
// Converted 2008-05-01 7:34:42Z to Local time 5/1/2008 12:34:42 AM
// Converted Thu, 01 May 2008 07:34:42 GMT to Local time 5/1/2008 12:34:42 AM
Since you have an UTC offset in your string, I would prefer to parse DateTimeOffset instead of DateTime. And there is no way to parse your GMT and (GMT Standard Time) parts without escape them.
Both DateTime and DateTimeOffset are timezone awareness by the way. DateTimeOffset little bit better than DateTime for this situation. It has UTC Offset but this doesn't guaranteed the timezone information because different timezones can have same offset value.
Even if they are, time zone abbreviations are not standardized. CST has several meanings for example.
string s = "Thu Jul 02 2015 00:00:00 GMT+01:00 (GMT Standard Time)";
DateTimeOffset dto;
if (DateTimeOffset.TryParseExact(s, "ddd MMM dd yyyy HH:mm:ss 'GMT'K '(GMT Standard Time)'",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out dto))
{
Console.WriteLine(dto);
}
Now, you have a DateTimeOffset as {02.07.2015 00:00:00 +01:00}

Correct format for DateTime.ParseExact

I have the below string which I need to parse to a DateTime:
Thu Aug 14 2014 00:00:00 GMT 0100 (GMT Summer Time)
I am unsure what format to supply to my DateTime.ParseExact to achieve this. The nearest I could find in standard date/time format string was Full date/time pattern (long time) as below but this does not work
DateTime.ParseExact("Thu Aug 14 2014 00:00:00 GMT 0100 (GMT Summer Time)", "F", CultureInfo.InvariantCulture); // FormatException
Any ideas?
If the offset is not important, I suggest you just truncate the string after the time.
It looks like the format should allow that by finding the first space after position 16 (the start of the time in your example; part way through the time if the day number is shorter):
int endOfTime = text.IndexOf(' ', 16);
if (endOfTime == -1)
{
throw new FormatException("Unexpected date/time format");
}
text = text.Substring(0, endOfTime);
DateTime dateTime = DateTime.ParseExact(text, "ddd MMM d yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
(I'm assuming the month and day names are always in English.)
If you are certain it will always be GMT summer time, couldnĀ“t you use this:
var str = "Mon Jan 05 1987 07:45:30 GMT+0000 (GMT Summer Time)";
var f = "ddd MMM dd yyyy hh:mm:ss 'GMT'K' (GMT Summer Time)'";
var dateTime = DateTime.ParseExact(str, f, CultureInfo.InvariantCulture);
Or if summer/winter can change but always GMT, regardless of offset.
var str = "Mon Jan 05 1987 07:45:30 GMT+0000 (GMT Summer Time)".Split('(')[0].Trim();
var f = "ddd MMM dd yyyy hh:mm:ss 'GMT'K";
var dateTime = DateTime.ParseExact(str, f, CultureInfo.InvariantCulture);

Need to convert following string into time format

I have the following two dates in string format.
1. 06 Mar 2013
2. 26 Mar 2013
I need to compare those two dates i.e if (06 Mar 2013 < 26 Mar 2013)
Is there any built-in function to convert string into C# Date and Time format?
You need to parse these two dates to DateTime Object, using DateTime.ParseExact with format dd MMM yyyy and then compare both.
string str1 = "06 Mar 2013";
string str2 = "26 Mar 2013";
DateTime dt1 = DateTime.ParseExact(str1, "dd MMM yyyy", null);
DateTime dt2 = DateTime.ParseExact(str2, "dd MMM yyyy", null);
if(dt1 < dt2)
{
//dt1 is less than dt2
}
You can also use the format d MMM yyyy, with single d which would work for both single digit and double digit day (e.g. 02 ,2 and 12 etc)
Yes there is. Try DateTime.Parse and DateTime.ParseExact methods. Here is the code sample:
string first = "06 Mar 2013";
string second = "26 Mar 2013";
DateTime d1 = DateTime.Parse(first);
DateTime d21 = DateTime.Parse(second);
var result = d1 > d21; //false
Use DateTime.ParseExact in the following way:
DateTime dt = DateTime.ParseExact(str, "dd MMM yyyy", CultureInfo.InvariantCulture);
Demo
CultureInfo.InvariantCulture is needed to ensure that it will be parsed successfully even if the current culture does not have english month names.

Categories