String to mmm-yy format of time in C# - 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.

Related

How to remove hour, minutes and seconds from a date

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

Formatting DateTime value in C#

I have a datetime variable like this:
DateTime date1 = DateTime.Now; // has 9.4.2014 01:12:35
I want to assign this to another datetime or change its value like this:
2014-04-09 13:12:35
How can I do?
Thanks.
EDIT : I don't want string variable. I want it Datetime format.
try this :
date1.ToString("yyyy-MM-dd HH:mm:ss")
Also look at the table below here http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
edit :
As Jon said (and which I didn't mention) :
you should add InvariantCulture ( if you dont want it to be used with current thread culture ) :
CultureInfo heIL = new CultureInfo("he-IL");
heIL.DateTimeFormat.Calendar = new HebrewCalendar();
CultureInfo dft = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = heIL;
Check these :
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss",CultureInfo.InvariantCulture);
result ( I live in israel) :
תשע"ד-ח'-ט' 13:32:31
2014-04-09 13:32:31
The code you've written just assigns a value to a variable. It doesn't return anything, and it doesn't have any inherent string representation. A DateTime value is just a date/time. It can be displayed in whatever format you want, but that's not part of the value of the variable.
It sounds like you're wanting to convert it to a string in a particular format, which you should do with DateTime.ToString - but only when you really need to. Try to keep the value as a DateTime for as long as possible. Typically you only need to convert to a string in order to display the value to a user, or possibly to use it in something like JSON. (If you find yourself converting it to a string for database usage, you're doing it wrong - make sure your schema has an appropriate data type for the field, use a parameterized query, and set the parameter value to just the DateTime - nor formatting required.)
The format you've specified looks like it's meant to be a machine-readable one rather than a culture-specific one, so I'd suggest:
string text = date1.ToString("yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture);
By specifying the invariant culture, we've said that the result shouldn't depend on the current culture (which otherwise it would) - this can make a big difference if the current culture uses a different calendar system, for example.
Something like the following, which is one of the constructors of the DateTime object:
d = new DateTime(2014, 5, 6, 5, 4, 30);
Which will set d to 06/05/2014 05:04:30. Its parameters are in descending size order, so Year, Month, Day, Hour, Minute then Seconds.
If you want to adjust the time by an amount, look at the add methods, or TimeSpans.
you can just use something like this to format the date:
date1.ToString("dd/MM/yyyy HH:mm:ss")
By using "HH" instead of "hh" you will get 24hour format on the hour.
Hope that helps.
Try this
DateTime date1 = DateTime.Now;
string datestring=date1.ToString("yyyy-MM-dd HH:mm:ss",CultureInfo.InvariantCulture)
http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
As a guess, the "returned" value of your DateTime object is seen by you, by hoovering over the variable in the IDE while debugging.
This is just another form of calling internally the default ToString() method of your DateTime object by the debugger. The value is the same.
See: system.datetime
DateTime Values and their string representations
Internally, all DateTime values are represented as the number of ticks (the number of 100-nanosecond intervals) that have elapsed since 12:00:00 midnight, January 1, 0001. The actual DateTime value is independent of the way in which that value appears when displayed in a user interface element or when written to a file. The appearance of a DateTime value is the result of a formatting operation. Formatting is the process of converting a value to its string representation.
Because the appearance of date and time values is dependent on such factors as culture, international standards, application requirements, and personal preference, the DateTime structure offers a great deal of flexibility in formatting date and time values through the overloads of its ToString method. The default DateTime.ToString() method returns the string representation of a date and time value using the current culture's short date and long time pattern.

Format Exception - string not recognized as a valid DateTime

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"

DateTime.TryParse - What was actually parsed?

I'm struggling a little bit in C# with DateTime.TryParse().
Essentially, given a string I need to extract the year and/or month and day in the current display culture. Sometimes I only get a year, or a month, or all three. Depending on what I get, I have a different control flow.
So far, I managed to parse a variety of strings into a DateTime; that isn't my problem.
My problem is that I wish to know WHAT was actually parsed (i.e. did I get a month or a year, or both).
The uninitialized DateTime defaults to 01/01/0001, and I cannot set everything to an invalid date, such as 99/99/9999 and then see what was filled.
I was thinking maybe I need to do regex, but the DateTime class provides that parsing for multiple cultures, which is very important in this project.
I've tried searching for this, but maybe I'm not using the right terms, because surely someone else must have had this issue before.
Update:
Here's some sample code of what I've got:
string strIn = Console.ReadLine();
DateTimeStyles enStyles = DateTimeStyles.AllowInnerWhite | DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite | DateTimeStyles.AssumeLocal;
bFound = DateTime.TryParse(strIn, CultureInfo.CreateSpecificCulture("en-US"), enStyles, out cDT);
Now, bFound will be true if something was parsed successfully. However, I need to know which parts of the date were parsed successfully
I dont understand you but are you looking for a specified format for your datetime?
string dateAndTimeFormat = "yyyy.MM.dd HH:mm:ss:fff"; // example of format
string dateAndTime = yourdatetimevalue;
DateTime toDateTime = DateTime.ParseExact(dateTime, dateTimeFormat, System.Globalization.CultureInfo.InvariantCulture)
How formats are used:
http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.71).aspx
EDIT 1
The tryparse returns true or false. False if it fails. Maybee that can be usefull?
Otherwise you can set the culture before the tryparse, if you are able to do so.
DateTime.TryParse(dateString, culture, styles, out dateResult)
Check the examples here :http://msdn.microsoft.com/en-us/library/9h21f14e.aspx
Under remarks:
"This method tries to ignore unrecognized data, if possible, and fills in missing month, day, and year information with the current date. If s contains only a date and no time, this method assumes the time is 12:00 midnight. If s includes a date component with a two-digit year, it is converted to a year in the current culture's current calendar based on the value of the Calendar.TwoDigitYearMax property. Any leading, inner, or trailing white space character in s is ignored. The date and time can be bracketed with a pair of leading and trailing NUMBER SIGN characters ('#', U+0023), and can be trailed with one or more NULL characters (U+0000)."
Hope some of that helps.
The DateTime.TryParse() returns value only on success.
So for below code example the variable dt is initialized to 01/01/0001 00:00:00 when declared.
When TryParse tries to extract date from string(MM/DD/YYYY format), and if it failes, then dt variable is having value 01/01/0001 00:00:00. Otherwise dt will contain the actual extracted datetime value (as in 2).
1)
DateTime dt;
DateTime.TryParse("23/15/2013", out dt);
// dt contains "01/01/0001 00:00:00"`
2)
`DateTime dt;
DateTime.TryParse("23/12/2013 6:25", out dt);
// dt contains "23/12/2013 06:25:00"`
There is no need to check WHAT was actually parsed.
Datetime value will be parsed if it's valid otherwise default datetime value will be returned.

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.

Categories