I receive Date and time from CSV file
The received Date format is YYYYMMDD (string) (there is no ":" ,"-","/" to
separate Year month and date).
The received time format is HH:MM (24 Hour clock).
I have to validate both so that (example) (i) 000011990 could be invalidated for date (ii) 77:90 could be
invalidated for time.
The question is ,
Regular expression is the right candidate for do so (or) is there any other way to achieve
it?
You're looking for DateTime.TryParseExact:
string source = ...;
DateTime date;
if (!DateTime.TryParseExact(source,
"yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date)) {
//Error!
}
You can use the same code to validate times, with the format string "HH:mm".
Your easiest solution would be to use
DateTime output;
if(!DateTime.TryParse(yourstring, out output))
{
// string is not a valid DateTime format
}
The DateTime.TryParse will attempt to convert your string to a DateTime variable, but it won't throw an exception if it fails - rather it return false if the string is not recognized as a valid DateTime.
I think a better way would be to use the date format class built into C#: DateTime.parse
You can use one of the TryParse methods of the DateTime struct. They will return false if they fail to parse.
Another option it use the ParseExact methods, but for those you need to specify a format provider.
Related
I've two types of dates, one in DateTime format and another in string format, both dates having the following format:
yyyy-MM-dd HH: mm: ss
I want to delete HH: mm: ss because I need to compare these dates in a loop to iterate through a database. The problem's that one of these dates is returned by a CalendarSelectionDate event, and the hour, minutes and seconds are even set to 0. Anyone have the best way to do this?
UPDATE:
if (DateTime.TryParseExact(reader["data"].ToString(), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt)){...}
The code behavior return an invalid date, in particular if I've 12/05/15 ... the code will return 1/01/0001
If you want to compare DateTime objects without the hour, you can use the Date property:
if (myDbDate.Date != myUserDate.Date) { }
You can also cast the date to a string using ToString(), but be aware that dates are a notoriously very hard thing to deal with when they are strings:
if (myDbDate.ToShortDateString() != myUserDate) { }
or if you are very sure of your format, you can use a custom date format:
if (myDbDate.ToString("yyyy-MM-dd") != myUserDate) { }
Update
Automatically parsing the string to a date (with DateTime.Parse or TryParse) has often resulted, in my own and personal experience, in very random results. You never seem to know which format .Net will decide on using (dd/MM or MM/dd ?).
Using ParseExact or TryParseExact solves this problem, and allows to work on the date further (add days, for instance). But for a simple comparison as in the initial question, since you're "locking" the date format in the code, it doesn't change much (maybe performance-wise, I don't know), and it's much more simple to cast the date to a string than the other way.
That being said, I went on the assumption that the comparison was "is different". If the comparison is "is later/earlier than", casting to a date would indeed be the right solution.
First you have to understand that DateTime does not have a format. It only contains information that describes a specific point in time. Formats apply to the string representations of a DateTime. For what you want you can use DateTime.Date which will return a new DateTime with the same year, month, and day values, but with the time set to 12 AM. That along with DateTime.ParseExact will allow you to parse the string to a DateTime then compare just the Date part.
var someDate = DateTime.ParseExact(stringValue, "yyyy-MM-dd HH: mm: ss");
if(someDate.Date != otherDate.Date)
{
}
To get the base date of any DateTime, simply use the Date property.
DateTime.Now.Date
I am using the code below to check the datetime and it is working fine in my machine but once after deployment, I am getting
"String was not recognized as a valid DateTime."
Please provide me the solution to work in all machine.
DateTime date1 = DateTime.Parse("16/05"); MM/dd
string todaydate = DateTime.Now.ToString("MM/dd");
if (Convert.ToDateTime(todaydate) > Convert.ToDateTime(date1.ToString("MM/dd")))
{ //Logic }
Honestly, since both answer didn't satisfied me, here is my two cent..
Let's look at your code line by line;
DateTime date1 = DateTime.Parse("16/05");
DateTime.Parse uses your CurrentCulture settings by default if don't provide any IFormatProvider as a second parameter on it's overloads. That means, if your one of standard date and time patterns of your CurrentCulture includes dd/MM (or your current culture DateSeparator since / format separator has a special meaning of replace me with current culture date separator) format, this parsing operation will be successful. That means this line might throws FormatException that depends on the current culture settings.
string todaydate = DateTime.Now.ToString("MM/dd");
DateTime.Now returns a local current time. With it's ToString() method you try to get it's string representation with MM/dd format. BUT WAIT! You used / format specifier again and still, you didn't use any IFormatProvider. Since this format specifier replace itself with current culture date separator, your todaydate might be 05/16, 05-16 or 05.16. That's totally depends on what date separator your current culture use.
Convert.ToDateTime(todaydate)
Convert.ToDateTime method uses DateTime.Parse explicitly. That means,since you didn't provide any IFormatProvider it will be use your CurrentCulture again and it's standard date and time formats. As I said, todaydate might be 05/16, 05-16 or 05.16 as a result. But there is no guarantee that your current culture parse this string successfully because it may not have MM/dd in it's standard date and time formats. If it parse "16/05" successfully, that means it has dd/MM format, in such a case, it definitely can't have MM/dd as a standard date and time format. A culture can't parse dd/MM and MM/dd formats at the same time. In such a case, it can't know that 01/02 string should parse as 2nd January or 1st February, right?
Convert.ToDateTime(date1.ToString("MM/dd"))
Same as here. As todaydate string, this will create "05/16" (it depends on current culture date separator of course) result and still there is no guarantee to parse this successfully.
And as said in comments, there is no point to parse your string to DateTime and get it's same string representation as well.
I strongly suspect you try to compare your current date is bigger than your parsed DateTime or not, you can use DateTime.Today property to compare with it. This property gets DateTime as current date part plus midnight as time part. For example;
DateTime dt;
if(DateTime.TryParseExact("16/05", "dd/MM", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
if(DateTime.Today > dt)
{
// Your operation
}
}
DateTime dt = DateTime.ParseExact("16/05", "dd/MM", CultureInfo.InvariantCulture);
if (DateTime.Today > dt)
{
// your application logic
}
DateTime dt = // From whatever source
if (DateTime.Now.Ticks > dt.Ticks)
{
// Do logic
}
I have an issue similar to this > Format exception String was not recognized as a valid DateTime
However, my spec requires a date format of ddMMyyyy, therefore I have modified my code but I am still getting the same error
DateTime now = DateTime.Now;
DateTime dt = DateTime.ParseExact(now.ToString(), #"ddMMyyyy", CultureInfo.InvariantCulture);
I am unclear why.
You code fails because you are attempting to parse a date in the format ddMMyyyy, when by default DateTime.ToString() will produce a format with both date and time in the current culture.
For myself in Australia that would be dd/MM/yyy hh:mm:ss p e.g. 11/10/2013 11:07:03 AM
You must realise is that the DateTime object actually stores a date as individual components (e.g. day, month, year) that only needs to be format when you output the value into whatever format you desire.
E.g.
DateTime now = DateTime.Now;
string formattedDate = now.ToString("ddMMyyyy", DateTimeFormatInfo.InvariantInfo);
For more information see the api doc:
http://msdn.microsoft.com/en-us/library/8tfzyc64.aspx
For ParseExact to work, the string coming in must match exactly the pattern matching. In the other question you mentioned, the text was coming from a web form where the format was specified to be exactly one format.
In your case you generated the date using DateTime.Now.ToString() which will not be in the format ddMMyyyy. If you want to make the date round trip, you need to specify the format both places:
DateTime now = DateTime.Now;
DateTime dt = DateTime.ParseExact(now.ToString("ddMMyyyy"), #"ddMMyyyy", CultureInfo.InvariantCulture);
Debug your code and look at what the result of now.ToString() is, it's is not in the format of "ddMMyyyy", which is why the parse is failing. If you want to output now as a string in the ddMMyyy format, then try now.ToSTring("ddMMyyyy") instead.
now.ToString() does not return a string formatted in that way. Try using now.ToString("ddMMyyyy").
You might be better off testing with a static string like "30041999"
What Convert.DateTime will convert the date 7/25/2010 12:00:00 it's current format is(MM/dd/yyyy HH:mm:ss)?
When I convert this string format to date time I am getting the error "string was not recognized as valid DateTime"
None. Dates are not stored internally as a certain format.
If you want to parse a string into a date, use DateTime.ParseExact or DateTime.TryParseExact (the former will throw an exception if the conversion fails, the second uses an out parameter):
DateTime myDate = DateTime.ParseExact("7/25/2010 12:00:00",
"MM/dd/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
If you want to display a certain format, use ToString with the format string.
So, if you have a date object that represents midday of the 25th of July 2010 (doesn't matter how it is represented internally) and you want to format it with the format string "MM/dd/yyyy HH:mm:ss" you do the following:
string formattedDate = myDate.ToString("MM/dd/yyyy HH:mm:ss");
If you need to use Convert.DateTime, I'll assume you're working with a string you want to convert to a date. So you might try this:
DateTime date = Convert.DateTime("7/25/2010 12:00:00 am");
string formattedDateString = date.ToString("MM/dd/yyyy HH:mm:ss")
I'm making no assumptions as to why you'd want to do this, except that, well, you have your reasons.
DateTime.TryParse() or DateTime.Parse() will do the trick.
Edit: This is assuming that you are going from a string to a DateTime object.
Edit2: I just tested this with your input string, and I receive no error with DateTime.Parse
I need to perform some date operations in ASP.net using C#.
The date i would enter should be of format 'Jul-05' (mmm-yy Format and type-string)...
how can i check with this????
Or how can i validate this with whatever user is entering as a string???
After validating that, i need to compare tht with a value in Database(say a column name buy_period which has a value (say) 04/31/2007).
How can i write a Query for comparing both?? (as both dates would be of different formats)
Can u pls help me in this ???
DateTime myDateTime = DateTime.ParseExact( input, "MMM-yy" );
You can then happily pass it to a stored procedure (etc.) as a parameter to do your comparison on the server (or just use the DateTime returned as the result of an existing query)
Use the TryParseExact method to validate the string and parse it to a DateTime value:
DateTime month;
if (DateTime.TryParseExact("MMM-yy", CultureInfo.InvariantCulture, DateTimeStyles.None, out month)) {
// parsing was successful
}
The DateTime value will use the first day of month and the time 0:00 to fill up a complete value, so a string like "jul-05" will be parsed into a complete DateTime value like 2005-07-01 00:00:00.0000, so it will be the starting point of that month.
To compare this to a date in the database you also need the starting point of the next month, which you get with:
DateTime nextMonth = month.AddMonths(1);
Now you can just compare a date to the starting and ending point of the month in this manner:
where date >= #Month and date < #NextMonth
The .NET framework has some nice methods on the DateTime struct :: Parse, TryParse, ParseExact, TryParseExact.
This info is discussed on MSDN.
Becuase you're providing a custom date string, we should then use the ParseExact or TryParseExact. The later doesn't throw an exception if it fails to parse.
So.. lets try this...
using System.Globalization;
CultureInfo MyCultureInfo = new CultureInfo("en-US");
string myString = "Jul-05";
DateTime myDateTime = DateTime.ParseExact(myString, "MMM-yy", MyCultureInfo))
Console.WriteLine();
the value myDateTime can then be passed to a database as a DateTime property and checked against that.
EDIT: Damn, beaten by Rowland by a min, as i was typing it!
EDIT 2: Please note the "MMM-yy". As stated on the MSDN page, MMM is "Represents the abbreviated name of the month as defined in the current System.Globalization.DateTimeFormatInfo.AbbreviatedMonthNames property." mmm (lower case) is invalid.
1: read this
2: is the column is a datetime or varchar?
well your validation and comparison have to be two different operations. so you could do alot of things for validation.
Validation Options:
1.) Split your string on "-" and check to see if the mmm part is in your list of months, and then check to see if the number is valid.
2.) Regular Expression, this is advanced but can be reduced to one line. Look up RegEx if you are interested.
After you've validated the string, convert it to a DateTime object and compare it to the other value using DateTime.Compare().
Hope that helps.
You could use
DateTime date = DateTime.ParseExact(value, "MMM-yy", null); //checked at http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
and then use that date in a sql command parameter.