I am trying to parse a string to Datetime, but it is not working and giving an error:
"String was not recognized as a valid DateTime."
The string is perfect.
Here is the code:
string deliv = DeliveryDateTextBox.Text;
string[] delivday = deliv.Split('-');
int year, month, day;
int.TryParse(delivday[0], out day);
int.TryParse(delivday[1], out month);
int.TryParse(delivday[2], out year);
string dtt = day + "/" + month + "/" + year;
DateTime datet = DateTime.ParseExact(dtt, "dd/MM/yyyy", null);
jobcard.DeliveryDate = datet;
I debugged the code and it is giving {01-01-0001 12:00:00 AM} on datet.
Besides the fact that you should be using new DateTime(year, month, day), or even DateTime.TryParseExact(deliv, "d-M-yyyy", .... ) on the original string...
Your call to DateTime.ParseExact() is failing because your input string has single-digit day and/or single-digit month, while your pattern dd/MM/yyyy demands double digits for both.
This can be fixed by using d/M/yyyy for the pattern, it will accept single and double digits. But please don't, see the first paragraph!
You over complicated things in this code.
Manually parsing the string to extract int values of day, month and year just to recombine them into a new string and parsing it makes no sense.
Simply try to parse the original string:
DateTime datet;
if(DateTime.TryParseExact(
DeliveryDateTextBox.Text,
"dd-MM-yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out datet))
{
// string was successfully parsed to dateTime.
}
There is no "perfect" DateTime String. How you can can/should represent a DateTime is dependent 100% on the CultureFormat of Windows, which can be totally different even within a langauge: For example en-gb and en-us disagree on what the decimal, thousand seperator are and in which order the date components should be listed.
Your whole code does not make a lot of sense. It seems you have some disjointed textboxes where the user inputs the day, month and year seperately. Then you parse them to int. Then you turn them into a string. Then you try to parse the string.
And at no point do you even check if the original user inputs are valid. That original parsing to Int might already fail. So you might try to parse 0/0/0 into a DateTime. To which your output is actually the perfect answer. And then there is stuff like anything before 1800 or so being literally not on the Gregorian calendar.
If you want the user to input a date, use a DatePicker element. Every GUI technology I know of has one. They give you DateTimes as return value. Do not try your custom workaround.
Related
i am fetching datetime value through xml like:
string time = "20150605020247+0000"
I want to convert into datetime value. I tried with DateTime.Parse, ParseExact, Convert.ToDateTime. It's not working, it's returning the error:
string was not recognised as valid datetime
You should use DateTime.ParseExact like this
DateTime theTime = DateTime.ParseExact(time, "ddMMyyyyHHmmss+ffff,CultureInfo.InvariantCulture);
You should be able to use DateTime.ParseExact, since you know the exact format of the string. If we assume it's year, month, day, hour, minute, second, and offset, then you can do something like:
var result = DateTime.ParseExact("20150605020247+0000", "yyyyMMddHHmmsszzz",
CultureInfo.InvariantCulture);
You need to use exact format specifier in your ParseExact method.
DateTime.ParseExact("20150605020247+0000", "yyyyMMddHHmmsszzz", System.Globalization.CultureInfo.InvariantCulture);
Fiddle: https://dotnetfiddle.net/cQJ9hN
EDIT:
Please check the standard DateTime formats used in .NET world: https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings plus check the source of your data how exactly are the string dates produced.
However most likely the '+####' part of your string is the local date UTC offset, not the fractions part of the time (as other answers suggest). So parsing the date by using the "yyyyMMddhhmmssffff" would produce wrong results.
I thought this would be easy:
I want to parse the following string format to DateTime:
"4/25/18 3:11 PM"
and it's a lot more difficult than I expected.
DateTime.Parse just returns an exception Input string not in the correct format
DateTime.TryParseExact is the closest I have come, and it can parse this exact string, but it does not account for when day, month, hour (etc) goes over (or below, depending on the mask) 9 since the mask has to match exactly or it will fail.
string input = "4/25/18 3:11 PM";
string input2 = "1/1/18 10:10 AM";
DateTime theDate;
DateTime.TryParseExact(input, "M/dd/yy h:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out theDate);
My next idea was to split out the 4, 25, 18 and add a 0 if they are < 10, and a 20 concatenated before the 18 but this seems overkill. It also leaves me with the time and making conditions based on if the tt is AM or PM.
EDIT: Based on some comments....
I have no control over the input string.
Convert.ToDateTime("25/4/18 3:11 PM") throws an exception {"String was not recognized as a valid DateTime."}
When I specified the input date as 4/25/18, the input format is clearly M/dd/yy. Unfortunately this can mean the input date can be MM/d/yy etc. We can assume it will always be Month / Day / Year..
TLDR: How can I parse input and input2 to a DateTime cleanly?
Thanks
You can change your code to be like this, and then it should accept both formats with single and double digits:
DateTime.TryParseExact(
input, "M/d/yy h:mm tt",CultureInfo.InvariantCulture, DateTimeStyles.None,
out var theDate);
The single character M, d,and h components in the format string allow for single or double digits.
Fiddle
If the code is executed in US Locale and the date string is known or expected to be a valid US date format:
Convert.ToDateTime("4/25/18 3:11 PM")
For other locales (assuming the input string is valid in the current culture) try this overload:
Convert.ToDateTime("25/4/18 3:11 PM", System.Globalization.CultureInfo.CurrentCulture)
However, based on your revision and comments if I understand correctly, you expect the date will always be in M/D/Y (US) format:
I have no control over the input string.
Convert.ToDateTime("25/4/18 3:11 PM") throws an exception {"String was not recognized as a valid DateTime."}
When I specified the input date as 4/25/18, the input format is clearly M/dd/yy. Unfortunately this can mean the input date can be MM/d/yy etc. We can assume it will always be Month / Day / Year.
Sure. In that case you're attempting to execute against an invalid US date, on a US culture. But if you can assume the date format provided in string will always be month/day/year, then you should be able to do:
Convert.ToDateTime("4/25/18 3:11 PM", new System.Globalization.CultureInfo("en-US"))
This seems to work whether month/day are provided in single or double-digit, and should return valid DateTime object based on assumed en-US date string.
I am trying to parse the date by using below code
DateTime mydate = DateTime.ParseExact(datetoconvert,"dd/mm/yyyy",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
but its output is wrong, the datetoconvert in above code is 30/Mar/2017 but output is 29/Jan/2017
looking forward for your valuable answers...
Lowercase mm means minute, use MM
DateTime mydate = DateTime.ParseExact(datetoconvert,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
If you want to output it as 30/Mar/2017(different topic):
string result = mydate.ToString("dd/MMM/yyyy", CultureInfo.InvariantCulture);
But note that / has a special meaning too(in Parse and ToString). It will be replaced with your current cultures date-separator which seems to be / but fails with a different. You can avoid it by specifying CultureInfo.InvariantCulture or by masking it by wrapping it with apostrophes:
DateTime mydate = DateTime.ParseExact(datetoconvert,"dd'/'MM'/'yyyy",System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat);
replace
"dd/mm/yyyy"
with
"dd/MMM/yyyy"
because "Jan" is matched by MMM instead of mm (for minutes)
Reference
"MMM" The abbreviated name of the month.
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
The date format is wrong. try "dd/MM/yyyy" instead of "dd/mm/yyyy"
If you need abbrivated month name, use "dd/MMM/yyyy"
I'm writing a C# class that will convert strings to dates. Pretty easy I guess. The class accepts formatstrings like "yyyy-MM-dd" and inputstrings like "2010-10-10"
However I have some cases that give me trouble:
format "yyyyMMdd" input "19950000"
or
format "dd-MM-yyyy" input "00-06-2001"
Note that these cases have zeroes ('00') for day and/or month, and that these cannot be converted to a DateTime. I'll need to replace them.
To handle theses cases I need to split the input string in the parts, one each for day, month and year, so I can set some default day and month (probably 01) if they are missing. But I need to use the formatstring to accomplish this.
So the question is, how can I split an inputstring in the components specified in the formatstring?
Thanks
[UPDATE] Using Joe's answer I came up with this:
string[] formats = { format, format.Replace("dd", "00").Replace("MM", "00"), format.Replace("dd", "00"), format.Replace("MM", "00") };
// Parse input
DateTime d = DateTime.ParseExact(txtDate.Text, formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
This uses the supplied format and creates alternative formats with zeroes ('00') for day, month and both day and month.
Thanks Joe!
If you have a well-defined set of formats, you can use DateTime.ParseExact, passing an array of format strings.
// Define all allowed formats
string[] formats = { "yyyyMMdd", "yyyyMM00", "yyyy0000" };
// Parse input
DateTime d;
d = DateTime.ParseExact("20100930", formats,
CultureInfo.InvariantCulture, DateTimeStyles.None);
d = DateTime.ParseExact("20100900", formats,
CultureInfo.InvariantCulture, DateTimeStyles.None);
d = DateTime.ParseExact("20100000", formats,
CultureInfo.InvariantCulture, DateTimeStyles.None);
Missing days / months will be set to a default of 1.
My approach would be to define various Regular Expressions and using a chain of responsibility design pattern, pass the value to the first, if matches it stops there and if not sends to the next one until one of them matches the string.
My regex pattern would separate date, month and year element and set a default value for each if it is 0.
Here for Chain-of-responsibility_pattern:
http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern
private const string Pattern_dd-mm-yyyy = "(\d\d)-(\d\d)-(\d){4}";
private const string Pattern_ddmmyyyy = "(\d\d)(\d\d)(\d){4}";
private const string Pattern_ddSlashmmSlashyyyy = "(\d\d)/(\d\d)/(\d){4}";
I don't fully understand your problem (I don't have the rep for a comment) but I can still give you some advices.
First of all, the DateTime class provides a ParseExact method (http://msdn.microsoft.com/en-us/library/w2sa9yss(v=VS.80).aspx) which accepts a formatting string for date and time. You can pass your format string to it
I don't clearly understand the part about the cases: do you need to accept timestamps in multiple formats? If so, you can try/catch until you find a match, or loop using the TryParseExact method which almost works the same.
Once you have a DateTime value, use the Year, Month and Day properties to get the components you've been searching in the input string
How could I get the current h/m/s AM time into a string? And maybe also the date in numeric form (01/02/09) into another one?
I'd just like to point out something in these answers. In a date/time format string, '/' will be replaced with whatever the user's date separator is, and ':' will be replaced with whatever the user's time separator is. That is, if I've defined my date separator to be '.' (in the Regional and Language Options control panel applet, "intl.cpl"), and my time separator to be '?' (just pretend I'm crazy like that), then
DateTime.Now.ToString("MM/dd/yyyy h:mm tt")
would return
01.05.2009 6?01 PM
In most cases, this is what you want, because you want to respect the user's settings. If, however, you require the format be something specific (say, if it's going to parsed back out by somebody else down the wire), then you need to escape these special characters:
DateTime.Now.ToString("MM\\/dd\\/yyyy h\\:mm tt")
or
DateTime.Now.ToString(#"MM\/dd\/yyyy h\:mm tt")
which would now return
01/05/2009 6:01 PM
EDIT:
Then again, if you really want to respect the user's settings, you should use one of the standard date/time format strings, so that you respect not only the user's choices of separators, but also the general format of the date and/or time.
DateTime.Now.ToShortDateString()
DateTime.Now.ToString("d")
Both would return "1/5/2009" using standard US options, or "05/01/2009" using standard UK options, for instance.
DateTime.Now.ToLongDateString()
DateTime.Now.ToString("D")
Both would return "Monday, January 05, 2009" in US locale, or "05 January 2009" in UK.
DateTime.Now.ToShortTimeString()
DateTime.Now.ToString("t");
"6:01 PM" in US, "18:01" in UK.
DateTime.Now.ToLongTimeString()
DateTime.Now.ToString("T");
"6:01:04 PM" in US, "18:01:04" in UK.
DateTime.Now.ToString()
DateTime.Now.ToString("G");
"1/5/2009 6:01:04 PM" in US, "05/01/2009 18:01:04" in UK.
Many other options are available. See docs for standard date and time format strings and custom date and time format strings.
You can use format strings as well.
string time = DateTime.Now.ToString("hh:mm:ss"); // includes leading zeros
string date = DateTime.Now.ToString("dd/MM/yy"); // includes leading zeros
or some shortcuts if the format works for you
string time = DateTime.Now.ToShortTimeString();
string date = DateTime.Now.ToShortDateString();
Either should work.
Method to get system Date and time in a single string
public static string GetTimeDate()
{
string DateTime = System.DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss");
return DateTime;
}
sample OUTPUT :-16-03-2015 07:45:15
DateTime.Now.ToString("h:mm tt")
DateTime.Now.ToString("MM/dd/yyyy")
Here are some common format strings
Be careful when accessing DateTime.Now twice, as it's possible for the calls to straddle midnight and you'll get wacky results on rare occasions and be left scratching your head.
To be safe, you should assign DateTime.Now to a local variable first if you're going to use it more than once:
var now = DateTime.Now;
var time = now.ToString("hh:mm:ss tt");
var date = now.ToString("MM/dd/yy");
Note the use of lower case "hh" do display hours from 00-11 even in the afternoon, and "tt" to show AM/PM, as the question requested. If you want 24 hour clock 00-23, use "HH".
string t = DateTime.Now.ToString("h/m/s tt");
string t2 = DateTime.Now.ToString("hh:mm:ss tt");
string d = DateTime.Now.ToString("MM/dd/yy");
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx