I have a string with a value in the format of
dd/mm/yyyy
Now I want to compare that to another string and check if they are equal, the other string can have the value of
dd/mm/yyyy
or sometimes when the day is between 1 and 9:
d/mm/yyyy
Sometimes when the month is between 1 and 9:
dd/m/yyyy
So there are a couple of instances where the string isn't equal but the actual date is.
First I only saw that in some cases when the day is between 1-9 it doesn't start with a zero so I did:
createdDate = dateField.value.ToString().Substring(0, 10);
createdDate = createdDate.Trim();
if (createdDate.Length == 9)
createdDate = "0" + createdDate;
but then I saw that it can be the same for month so there must be a better way to check this?
Why not just parse both, one with the format string "dd/MM/yyyy" and one with the format string "d/M/yyyy" and compare the returned DateTime values? After all, the date being represented is the important part, not the string representation, presumably.
You should use DateTime.Parse to convert both values to dates and then compare the dates.
DateTime.Parse("01/01/2001") == DateTime.Parse("1/1/2001")
When it are strings, that represent dates, why don't you try to parse them to a date, and compare the date instances that you become ?
you just have to make sure that you use the correct pattern when parsing.
Check out the DateTime.TryParse method.
I'd parse both dates into DateTimes and then compare them, that way you don't have to worry about different formats in the compare.
First, parse the strings into values of type DateTime (DateTime.ParseExact), then use the standard equality comparer (==) to compare the dates.
Related
I use OpenXml to fill my database with values. One of my generic functions converts each cell's value (string) to a proper type:
convertedValue = Convert.ChangeType(value, realType);
Everything works fine unless it's a date. Sometimes OpenXml reads a date cell like this: 01/01/2019 and conversion works fine. Sometimes it converts to a number like this: 43466. I know that this number represents how many days passed since 1900 but it breaks my function. It cannot convert this number to a DateTime.
I want to add a conversion for OA Dates like this:
convertedValue = DateTime.FromOADate(doubleValue);
The problem is how do I check that the value read from the cell is an OA Date?
I was thinking of checking the length of the value variable and verifing that all characters are numbers. Is there a better way to solve this problem?
Use TryParseExact to determine the format. If it doesn't parse exactly in the format provided, it will return false. Then we know we can use FromOADate method from DateTime
if(DateTime.TryParseExact(valueString, "mm/dd/yyyy", enUs, DateTimeStyles.None, out dateTime))
{
// Handle standard date format
}
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 trying to figure out how it is that I can keep the 0's or add them when I grab a date.
What Im getting is this:
6/15/2010
What I'm tring to get is:
06/15/2010
I have added it so that it checks the length to and if its less than 6 (im stripping the "/") it pads the left side. That solves the issue when the month is a single digit, but what about when the date is a single digit.
My ultimate goal is to have a date such as:
1/1/2010
read out like:
01/01/2010
Any suggestions would be greatly appreciated.
Use a custom format : dd/MM/yyyy, or in your case MM/dd/yyyy. Note the capital M, the small m gets you the minutes.
string s = DateTime.Now.ToString("MM/dd/yyyy");
You need to use a custom DateTime format string:
string str = someDate.ToString("dd/MM/yyyy");
It depends on the format of date you are using.
For instance, dd/MM/yyyy will produce 01/05/2009 and d/M/yyyy would produce 1/5/2009
A complete reference can be found there : http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
You want something like this:
string myDate = "1/1/2010";
DateTime date = DateTime.Parse(myDate);
string formattedDate = date.ToString("MM/dd/yyyy");
If the starting date is some other unrecognized format you could use DateTime.ParseExact();
Use DateTime.ParseExact() to parse the string into a valid datetime object and then use DateTime.ToString("dd/MM/yyyy") to get result in desired format.
I am trying to convert a string into datetime with the following C# code,
DateTime dTo = DateTime.ParseExact(dateTo, "mm/dd/yyyy", CultureInfo.InvariantCulture);
eachtime I pass dateTo as 1/1/2010 it fails, instead it needs the string to be 01/01/2010.
What string format should I use to support both 01/01/2010 and 1/1/2010?
Using the following date format expression will allow you to use either single or double digit day and month elements.
"M/d/yyyy"
Note that the capital M is significant - a lower case m is the placeholder for minutes.
You will find more information related to date format strings here.
You can use the following Powershell command to test them.
[DateTime]::ParseExact('01/01/2010', 'M/d/yyyy', $null)
Capital M is month, little m is mins i think.
But to the point of the question, use Parse. ParseExact implies you know the exact format of the input.
You could try this format: MM/dd/yyyy, but I think there's no single format string that could support both inputs. You could test if the length of your dateTo string is less than 10 characters use M/d/yyyy, otherwise MM/dd/yyyy.
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.