How to remove hour, minutes and seconds from a date - c#

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

Related

Inconsistency when parsing DateTime in the same format

I have the following strings:
10/10/2021 00:00:00 and 18/11/2021 23:59:59
I have this code:
bool first = DateTime.TryParse("10/10/2021 00:00:00",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out DateTime firstDate);
bool second = DateTime.TryParse("18/11/2021 23:59:59",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out DateTime secondDate);
Console.WriteLine(firstDate + " --- " + secondDate);
The output is:
10/10/2021 12:00:00 AM --- 1/1/0001 12:00:00 AM
As you can see the second date is not properly parsed, even though it's in the same format. What is the reason for that and how can I fix it?
As you can see the second date is not properly parsed, even though it's in the same format.
Here my two cents.
Programming languages and frameworks are not smart enough to know which kind of format data you applied, specially for dates, times, numbers etc.. If you provide these data, you kinda have to provide the proper format as well so they can do their job. You "said" the same format, but you didn't apply any format in your code. So, as we humans, we know (at least you told us) but the computer don't know.
Let's look what TryParse(String, IFormatProvider, DateTimeStyles, DateTime) documentation says;
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified culture-specific format
information and formatting style, and returns a value that indicates
whether the conversion succeeded.
You didn't supply format information you supplied IFormatProvider as InvariantCulture. So, what are these "culture specific formats"?
Well, most of them are returns with GetAllDateTimePatterns method (but not all of them) but be aware because documentation says;
You can use the custom format strings in the array returned by the
GetAllDateTimePatterns method in formatting operations. However, if
you do, the string representation of a date and time value returned in that formatting operation cannot always be parsed successfully by the
Parse and TryParse methods. Therefore, you cannot assume that the
custom format strings returned by the GetAllDateTimePatterns method
can be used to round-trip date and time values.
So, if you run;
CultureInfo.InvariantCulture.DateTimeFormat.GetAllDateTimePatterns().Dump();
*Dump is just an extension method of LINQPad by the way, it just outputs to the console.
You will get a lot of datetime patterns, but for our case, the important one is we get MM/dd/yyyy HH:mm:ss format for InvariantCulture.
As you can see, your 18/11/2021 23:59:59 data doesn't match with MM/dd/yyyy HH:mm:ss format because there is no 18th month on Gregorian calendar which is a DateTime instance belongs internally.
Your second parsing fails by the way, that's quite different just saying "the second date is not properly parsed" and this is how DateTime.TryParse method works as explained in the documentation;
When this method returns, contains the DateTime value equivalent to
the date and time contained in s, if the conversion succeeded, or
MinValue (which is 1/1/0001 12:00:00 AM) if the conversion failed. The conversion fails if the s
parameter is null, is an empty string (""), or does not contain a
valid string representation of a date and time.
So, best way to handle this to supply a "specific" format using with DateTime.TryParseExact method or one of its overloads like;
bool first = DateTime.TryParseExact("10/10/2021 00:00:00",
"dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out DateTime firstDate);
bool second = DateTime.TryParseExact("18/11/2021 23:59:59",
"dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out DateTime secondDate);
The default DateTime format is 'MM/dd/yyyy' and since you have the date in 'dd/MM/yyyy' format it gives you the output.
Maybe try changing the date format input as 11/18/2021 23:59:59

C# - Date/Time Formatting

Using C#, I am trying to format a date in to the following string format:
YYYYMMDD_HHMM.xlsx
Here is my code:
DateTime.Today.AddDays(0).ToString("yyyymmdd") + "_" + DateTime.Today.AddDays(0).ToString("hhmm")
Here is my output:
20130027_1200.xlsx
Month is not correct, nor is the time.
You're using mm, which is minutes, not months - and you're trying to print the time using DateTime.Today, which always returns midnight at the start of the day.
It's not clear why you're adding 0 days, either. I'd use:
DateTime now = DateTime.Now;
string name = now.ToString("yyyyMMdd'_'HHmm'.xlsx'");
(The ' quoting for the _ isn't strictly necessary, but personally I find it simplest to take the approach of quoting everything that isn't a format specifier.)
Or:
DateTime now = DateTime.Now;
string name = string.Format("{0:yyyyMMdd}_{0:HHmm}.xlsx", now);
Note the use of HH instead of hh to get a 24-hour clock rather than 12-hour, too.
Additionally, consider using UtcNow instead of Now, depending on your requirements. Note that around daylight saving transitions, the clock will go back or forward, so you could end up with duplicate file names.
Also note how in my code I've used DateTime.Now once - with your original code, you were finding the current date twice, which could have given different results on each invocation.
Finally, you might also want to specify CultureInfo.InvariantCulture when you format the date/time - otherwise if the current culture is one which doesn't use a Gregorian calendar by default, you may not get the results you were expecting.
DateTime.Today returns DateTime with all time-related properties set to 0. Use DateTime.Now instead.
Property value
An object that is set to today's date, with the time component set to 00:00:00.
from DateTime.Today Property
Use MM in your format to get month. mm returns minutes. You can check all format specifiers on MSDN: Custom Date and Time Format Strings

A type to create DateTime Object in particular format in C#.NET

In my project, I am in need of creating a DateTime object in below format.
"MM/dd/yy hh:mm tt" (without seconds and the year in two digit format)
When I am creating a date time object with a string (like "7/12/12 04:50 AM"), the created date time object is in the format of complete date time structure. (7/12/2012 04:50:00 AM)
Is there any way to create date time object (not string format) in particular format?
No, It has predefined date and time value (such as the year, month, and day, or the number of ticks).
There is no way other than converting it in string with the format you are in need of.
DateTime dat1 = new DateTime();
// The following method call displays 1/1/0001 12:00:00 AM.
It uses the default DateTime.ToString() method to display the date and time using the short date and long time patterns.
The DateTime object does not have any format. It has members and those members will have values. If you don't supply those values, they will be 0. The only way you can hide them is to format the DateTime object to a String where those values will not be shown. But in the DateTime object itself, they will still exist.
No, the DateTime object stores a date and time in a predetermined format.
What you are trying to do really should be done when displaying the date.
Perhaps if you explain the real problem you're trying to solve, someone can suggested a better alternative.
you can try by converting this to string and give your specified format as follows:
datetime dt=new datetime();
string dateval=dt.tostring("MM/dd/yy hh:mm tt")
thanks.

C# - Regular Expression validating Date and Hour

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.

String to mmm-yy format of time in C#

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.

Categories