C# DateTime FormatException for dd MMM yyyy - c#

I am having a string "10-Dec-2013". I just want to convert it into Datetime type. The format should be "dd MMM yyyy".
I used the following code.
DateTime watchDate = DateTime.ParseExact("18-Nov-2013", "dd MMM yyyy", CultureInfo.CurrentCulture);
But i am getting FormatException. Where am i going wrong?

You need the dashes:
DateTime watchDate = DateTime.ParseExact("18-Nov-2013", "dd-MMM-yyyy", CultureInfo.InvariantCulture);
// ^ ^
The format has to match your input.. which contains dashes.
If you want to re-store it in a string (not sure why you want to do that, since you already have the string you want) then you need to format it again:
string date = watchDate.ToString("dd-MMM-yyyy");

Related

convert date time to format ddd MM/dd/yyyy HH:mm:ss

In the below code snippet I'am passing string value "item.Date" to string "Date"
I wanted to convert it to this format ddd MM/dd/yyyy HH:mm:ss.
converting to string and as well the above format was not going well i guess.
I tried using:
DateTime dateformatted = DateTime.ParseExact(item.Date, "ddd dd MMM yyyy h:mm tt", null);
it showed error. Can anyone help
foreach (var item in data)
{
model.Add(new MailDetailDTO
{
Attributes = item.Attribute1,
Date = item.Date,
From = item.SentFrom,
FromOrg = item.OrganizationName,
IsConfidential = item.IsConfidential,
MailID = item.MailHeaderID,
}
}
This is what the ParseExact API documentation on MSDN has to say :
The format of the string representation must match the specified
format exactly.
This means that there is a certain mismatch in the format you have stored the date time value in item.Date string property and the custom date time format ddd dd MMM yyyy h:mm tt which you're passing as argument to ParseExact API.
Have a look at the below code snippet:
private static void DateTimeForatError()
{
var item = "Sun 22-May-2016 3:52 AM";
DateTime dateformatted = DateTime.ParseExact(item, "ddd dd MMM yyyy h:mm tt", null); //results in exception
}
Date time string value present in item variable looks parseable but the next line results in String was not recognized as a valid DateTime. error. That is because I'm using - hyphen as the delimiter for day, month and year while the custom format string dd MMM yyyy uses space . As long as there is even a single difference in the way I have stored date time string value in item variable which is not complying with the custom format string ddd dd MMM yyyy h:mm tt it will burst. The moment I make the value of item to Sun 22 May 2016 3:52 AM it succeeds. You just change the value of item.Date in the object of MailDetailDTO object to match it with the custom date time string format to get rid of the error OR change the custom date time format string that you are passing to the PraseExact API to match it with the format of date time value coming in item.Date from your back-end data.

Javascript date to ASP.NET date: String was not recognized as a valid DateTime

I'm passing a date back to my MVC controller via AJAX using:
date.GetDate().toLocaleDateString();
This will produce a value of "4/5/2014"... When I try and convert this inside my controller using:
DateTime myDate = DateTime.ParseExact(request.Params["myDate"], "dd/MM/yyyy", CultureInfo.InvariantCulture);
I get "String was not recognized as a valid DateTime." Which makes sense because the format of the string isn't correct... When I hardcode the string to: "04/05/2014" it will fix my issue.
Is there anyway to fix the format coming from javascript without have to rip the string apart into day, month, year and reassembling it in the proper format?
Any advice would be much appreciated!
Thank you
Additional info:
string myRequestDate = request.Params["myDate"];
string myViewBagDate = ViewBag.MyDate;
//This line passes
DateTime date1 = DateTime.ParseExact(myViewBagDate, "d/M/yyyy", CultureInfo.InvariantCulture);
//This line fails...
DateTime date5 = DateTime.ParseExact(myRequestDate, "d/M/yyyy", CultureInfo.InvariantCulture);
When I add a watch on both of the string variables the values are identical in every way I can see but for some reason the second line fails...
So when I look at the myRequestDate as a char array I see there is a bunch of stuff in there that doesn't look like a date at all...
Character 8206 (U+200E) is the Unicode LEFT-TO-RIGHT MARK (which is invisible).
Try to figure out where it's coming from and remove it at the source.
As a workaround, you can strip out those characters before you parse the date:
myRequestDate = myRequestDate.Replace("\u200E", "");
DateTime date5 = DateTime.ParseExact(myRequestDate, "d/M/yyyy", CultureInfo.InvariantCulture);
Just change the format string you use to match what you get from the JavaScript date.
DateTime.ParseExact(request.Params["myDate"], "d/M/yyyy", CultureInfo.InvariantCulture);
This code:
var d=new Date();
console.log(d.toString());
In windows 8.1 Chrome does this output
"Wed Jun 04 2014 20:38:23 GMT+0200 (Hora de verano romance)"
But in Cromium in Kubuntu
"Wed Jun 04 2014 20:38:23 GMT+0200 (CEST)"
Very similar, but other browser return diferent kind of formats, i use this function, this work fine with various kinds of formats.
public static DateTime ParseDate(string value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
string[] formats = {"ddd MMM dd yyyy hh:mm:ss 'UTC'zzz",
"ddd MMM d yyyy hh:mm:ss 'UTC'zzz",
"ddd MMM d hh:mm:ss 'UTC'zzz yyyy",
"ddd MMM dd hh:mm:ss 'UTC'zzz yyyy",
"ddd MMM dd yyyy hh:mm:ss 'GMT'zzz",
"ddd MMM d yyyy hh:mm:ss 'GMT'zzz",
"ddd MMM d hh:mm:ss 'GMT'zzz yyyy",
"ddd MMM dd hh:mm:ss 'GMT'zzz yyyy",
"dd-MM-yyyy",
"yyyy-MM-dd'T'hh:mm:ss"
};
DateTime fecha;
//Try the default
if (!DateTime.TryParse(value, out fecha))
{
if (!DateTime.TryParseExact(value, formats,
new CultureInfo("en-US"),
DateTimeStyles.None, out fecha))
{
if (value.Length > 24)
{
return ParseDate(value.Substring(0, 24));
}
else
{
throw new FormatException();
}
}
}
return fecha;
}
Use the following code at the client side:
(date.GetDate()).toDateString();
At your controller side:
var date = Convert.ToDateTime(Request.Params["myDate"]);

DateTime TryParseExact a string containing a 3 letter month

I am writing an extension method to parse a specific string which contains a date and a time into a DateTime object using the DateTime.TryParseExact() Method.
An example of the format is as follows:
"29 November 2013 20:04"
The code I am using to parse it to a DateTime is:
public static DateTime MyToDateTime(this string value)
{
DateTime converted;
DateTime.TryParseExact(value, "dd MMM yyyy hh:mm", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out converted);
return converted;
}
The result is always DateTime.Min (i.e 0001-01-01 00:00:00.000)
I cant figure out what is wrong with my format string. Any help would be appreciated.
from your comments:
if you want to parse 3 Letter Month use MMM.
if you want to parse 24-Hour format you should use HH instead of hh.
Try This:
DateTime.TryParseExact(value, "dd MMM yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out converted);
There are two problems I see:
November is not a 3-letter month—that would be Nov. To parse a full date name, use MMMM.
To parse a 24-hour time use HH.
This should work:
DateTime.TryParseExact(value, "dd MMMM yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out converted);
Further Reading
Custom Date and Time Format Strings
Try adding an extra M and a capital H
DateTime.TryParseExact(value, "dd MMMM yyyy H:mm", .....
See here for more info: How can I visualize the way various DateTime formats will display?
MMM stands for the abbreviated name of the month, so it's not what you're looking fore. Use MMMM instead.
Find all custom Date and Time format string on MSDN: Custom Date and Time Format Strings.
You should also check the value returned by TryParseExact method. It returns false when parse failed and true when it was performed without any problems.
And hh should be HH to parse hour part of your input.

C# DateTime Conversion from yyyy-MM-ddTHH:mm:ss to dd MMM yyyy

How to convert "yyyy-MM-ddTHH:mm:ss" into "dd MMM yyyy" format? For Instance, i want to convert 2013-04-16 05:30:05 into 16 April 2013. What is the correct method to achieve this?
First ParseExact then do ToString (I assume that you have string object, if you have DateTime object, skip first line)
var dateTime = DateTime.ParseExact(yourDateString, "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture);
var yourNewString = dateTime.ToString("dd MMM yyyy");
Note that representation of DateTime you see in debugger is dependant on your current culture.
First, a DateTime has no format. But if you've already a string that represents a DateTime with the format yyyy-MM-ddTHH:mm:ss and you want to convert it to a string-date with format dd MMM yyyy you need to parse it to DateTime first.
Therefore use DateTime.ParseExact:
DateTime dt = DateTime.ParseExact("2013-04-16 05:30:05", "yyyy-MM-dd HH:mm:ss", null);
Now you can use DateTime.ToString:
string result = dt.ToString("dd MMM yyyy");
Note that you need to pass a different CultureInfo object to ParseExact/ToString if you want to parse with another DateTimeFormat than your current (f.e. force english month names instead of german: dt.ToString("dd MMM yyyy", CultureInfo.InvariantCulture)).
As others mentioned, a DateTime has no format. To parse a string literal to a Date you need to call DateTime.Parse (if the string is in a culture-specific format) or DateTime.ParseExact if you need to pass a format string.
The format can be a custom format like yyyy-MM-dd HH:mm:ss or one of the standard format strings, eg. s for yyyy-MM-ddTHH:mm:ss.
2013-04-16 05:30:05 it not in one of the standard formats, so you have to parse by passing a custom format string:
var dt = DateTime.ParseExact("2013-04-16 05:30:05", "yyyy-MM-dd HH:mm:ss", null);
On the other hand, yyyy-MM-ddTHH:mm:ss is the s standard format so you can just write:
var dt = DateTime.ParseExact("2013-04-16T05:30:05", "s", null);

Convert date from MMM DD, YYYY to mm/dd/yy

i got date in my db in the form of MMM DD,YYYY
String thisDate1 = "Jan 05, 2009";
in order to get arithmetic operations such as add days i have to change it to standard format i.e mm/dd/yy. how can i do this. please help
Your string is fine as-is, you can use DateTime.Parse to convert it to a DateTime object which you can do your arithmetic on, like so:
var thisDate = DateTime.Parse(thisDate1);
var nextDate = thisDate.AddDays(1);
var nextDateAsString = nextDate.ToString("MMM dd, yyyy");
Also be careful with your casing, your current string is actually in MMM dd, yyyy format. DD would actually give you the letters DD themselves, as would YYYY. mm is minutes, while MM is for months. You can find more details on this on MSDN.
Also, as #HansPassant pointed out, you don't want to be storing your dates in a string until the last possible moment.

Categories

Resources