I have an internal business process that my finance dept runs. To kick it off they input a Date in the format of yyyyMM or 201009. I want to check for a valid date from that string but so far I got nothing.
I am currently exploring breaking the string up, taking the first 4 and checking that they are between 1990 and 2050(as example) and then the last 2 and checking that it is between 01 and 12.
Is there a better way?
You can use DateTime.TryParseExact to see if it can be parsed correctly:
bool isValid = false;
DateTime dateValue;
if(DateTime.TryParseExact("201009", "yyyyMM", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dateValue))
{
// DateTime parsed, dateValue contains the parsed DateTime
// Can validate dateValue against business rules at this point
isValid = (dateValue <= DateTime.Now && dateValue >= DateTime.Now.AddYears(-5));
}
If you would rather get an exception, you can use DateTime.ParseExact:
// Next line throws exception if format not correct
DateTime.ParseExact("201009", "yyyyMM", CultureInfo.InvariantCulture);
You can use a regular expression:
if (Regex.IsMatch(input, #"^(199\d|20[0-5]\d)(0[1-9]|1[0-2])$")) {
// valid input between 199001 and 205912
}
I would go with DateTime.ParseExact:
DateTime d = DateTime.ParseExact("201009", "yyyyMM", System.Globalization.CultureInfo.InvariantCulture);
The problem here is that the format "yyyyMM" cannot represent a specific DateTime. So the parsing methods built in to DateTime will do you no good.
Update: Never mind; I stand corrected. DateTime.TryParseExact will work just fine (which is ironic, if you ask me); it'll interpret your string to represent the first day of the given month.
I would do what you're describing: parsing the string into the two numeric components and simply compare those values to whatever range you require them to fall within.
I'd be tempted perform this as a number range problem:
UInt32 val;
if (input.Length != 6
|| !UInt32.TryParse(input, out val)
|| val > 205012
|| val < 199001
|| val % 100 > 12
|| val % 100 == 0) {
// Invalid...
}
Related
I am trying to filter through things by date. I have 2 DateTimePicker called FromDate and ToDate. I have an array and within one of the array (str[10]) is a date, I tried converting the string into a datetime format but I still get the error:
System.FormatException: 'String was not recognized as a valid DateTime.'
The string within str[10]:
str[10] = "9/22/2017 18:24";
My current code:
string[] date = str[10].Split(' ');
DateTime dateSpec = DateTime.ParseExact(date[0], "MM/dd/yyyy", CultureInfo.CurrentCulture);
if (dateSpec >= FromDate.Value && dateSpec <= ToDate.Value)
{
//Do Something
}
I am not so sure what to do as most forums suggest more or less the same thing. I'm not sure where the error is. I checked the array and the string does not have any spaces as well, thinking that it may have been the reason as to why there was an error
The MM in "MM/dd/yyyy" means the month component will be padded with a 0, if necessary, to make it two digits long. Your input, "9/22/2017", uses only a single-digit month and so doesn't match that format. If you change the format to "M/dd/yyyy" it parses successfully.
Also, you don't need to truncate the time portion yourself; if the time format is consistent (HH : mm) then just parse it and use the Date property to get a DateTime for midnight of the same day...
DateTime dateSpec = DateTime.ParseExact(str[10], "M/dd/yyyy HH:mm", CultureInfo.CurrentCulture);
if (dateSpec.Date >= FromDate.Value && dateSpec.Date <= ToDate.Value)
{
//Do Something
}
Depending on how str is populated (e.g. user input) also consider using DateTime.TryParseExact(), which returns false upon failure rather than throwing a FormatException...
if (DateTime.TryParseExact(str[10], "M/dd/yyyy HH:mm", CultureInfo.CurrentCulture, DateTimeStyles.None, out DateTime dateSpec))
{
// Handle parsing success
if (dateSpec.Date >= FromDate.Value && dateSpec.Date <= ToDate.Value)
{
//Do Something
}
}
else
{
// Handle parsing failure
}
dateSpec is declared at the point it is passed as an out parameter, which is possible since C# 7.0.
I managed to get it working by adding this block of code from another coder's suggestion on another platform
string[] formats = { "M/d/yyyy HH:mm", "M/dd/yyyy HH:mm", "MM/d/yyyy HH:mm", "MM/dd/yyyy HH:mm" };
DateTime dateSpec = DateTime.Now;
if (DateTime.TryParseExact(str[10].ToString(), formats, System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dateSpec))
{
if (dateSpec.Date >= FromDate.Value.Date && dateSpec.Date <= ToDate.Value.Date)
{
//Do Something
}
}
else
{
MessageBox.Show("Error");
}
I realize this may have been answered before, and I may just not be searching for the answer properly, so my apologies if this is a duplicate. This is for a c# webform.
I've got a datetime, set to now, and rounded up the nearest 30 minutes:
DateTime dtNow = RoundUp(DateTime.Now, TimeSpan.FromMinutes(30));
I'm splitting the datetime into its component parts, using M:YY tt (no preceding 0 on the month, two digit year, 12 hr am/pm)
DateString = dtNow.ToString("M/dd/yy");
TimeString = dtNow.ToString("h:mm tt");
What I want do to is simple, I want to see if that TimeString falls between 7:00pm and 5:59am, just need to round it to 6:00am of the following day (unless its past midnight, in which case 6:00am of that day).
Can anyone help me out, or at least point out where its already answered?
You should really stick to DateTime. What you want using string will always need to parse again that string into a DateTime to implement your logic.
A simple solution:
public static DateTime GetRoundedDate(DateTime originalDate)
{
if(originalDate.Hour > 19)
return originalDate.Date.AddDays(1).AddHours(6);
else if (originalDate.Hour < 6)
return originalDate.Date.AddHours(6);
return originalDate;
}
So now you may call:
DateTime dtNow = RoundUp(DateTime.Now, TimeSpan.FromMinutes(30));
var rounded = GetRoundedDate(dtNow);
DateString = rounded.ToString("M/dd/yy");
TimeString = rounded.ToString("h:mm tt");
Just look at the time properties on your DateTime object.
if (dtNow.Hour >= 19 || (dtNow is tomorrow && dtNow.Hour <= 7)) {
//do your stuff
}
where "is tomorrow" is something like dtNow.Date == DateTime.Today.AddDays(1)
I have some automated C# windows services to upload text to the database. The 'text' is generated by a third party application where we don't have any control.
My issue is that the text contains a column for date.
The default date format is DD/MM/YY. But some times we get MM/YY/DD
Is there any tricky way to identify or convert MM/YY/DD to DD/MM/YY. The data might only contain date for three, four days. So I plan to check if the date is in tolerance with three or four days, it will be accepted. Other wise manually correct it.
For example,
14/08/17 is accepted
08/17/14 is not accepted. Logic should convert this to 14/08/17
Any ideas ?
You could try and parse with the good format, if it goes ok there is no problem, it will return the date. If it goes wrong, you tryparse with the 'secondary format'. If everything goes ok, it will return the date.
Note that if the parsed date it's more than 3 days ahead, it won't count as a valid date and will return null.
if(DateTime.TryParseExact(input, "dd/MM/yy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue)
{
int daysBetween = (dateValue-DateTime.Now).Days
if(daysBetween < 4)
{
return dateValue
}
}
if(DateTime.TryParseExact(input, "MM/yy/dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue)
{
int daysBetween = (dateValue-DateTime.Now).Days
if(daysBetween < 4)
{
return dateValue;
}
}
return null
If null gets returned, you'll have an invalid date, if not, that will be the parsed date
I have a program that has synchronization. That means I need to save the last synchronization date and check if it needs to be synchronized.
So, I have this:
IS.SaveContactsRetrieveDate(DateTime.Now.ToString("dd.MM.yyyy"));
Saving a date to Isolated Storage.
Then, when I call IF:
DateTime toDate = DateTime.Now;
string contactsRetriveDate = IS.ReadContactsRetriveDate();
if (contactsRetriveDate == "" || DateTime.Compare(toDate, DateTime.Parse(contactsRetriveDate)) == 1)
{
MessageBox.SHow("");
}
The problem is that when user changes the region code fails here:
DateTime.Compare(toDate, DateTime.Parse(contactsRetriveDate))
With incorrect input error.
I understand that Latvian format is dd.MM.yyyy and USA MM/dd/yyyy - but I can't find a solution...
I need all datetime parsed in one format, so I could add days, weeks and compare date.
You should serialize and deserialize your date in a culture-independent manner (where "d" is the "Short date pattern" of the Standard Date and Time Format Strings):
var s = DateTime.Now.ToString("d", CultureInfo.InvariantCulture);
var d = DateTime.Parse(s, CultureInfo.InvariantCulture);
You can use ParseExact
DateTime.ParseExact(datestring, "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
you already know format so you can go for this, but make sure the string is in same format and never changes.
u can try this one:
DateTime toDate = DateTime.Now;
string contactsRetriveDate = IS.ReadContactsRetriveDate();
DateTime contactsRetriveDat = Convert.ToDateTime(contactsRetriveDate);
if (contactsRetriveDate == "" || toDate.CompareTo(contactsRetriveDat)==0)
{
MessageBox.SHow("");
}
I would like to know a simple algorithm to check if the given instance of datetime lies between another two instances in C#.
Note:
I skimmed though this How do I check if a given datetime object is "between" two datetimes? and it was for python and many more for php. Most of the other questions were regarding difference between the two.
Details:
I am more specific about the time, date does not matter to me. For example i got DataBase entry for a staff who works between 10:00 Am - 9:00 Pm and I would like to know which staff is engaged in class at the given time like 2:00 Pm. Now this would return me the staff's details who are engaged at this time.
Edit
After accepting the answer(been more than year back), i realized i had incorrectly described the problem. But all i think that was to be done back then was to do date and time comparison. So answers by both Jason and VikciaR work.
DateTime.Ticks will account for the time. Use .Ticks on the DateTime to convert your dates into longs. Then just use a simple if stmt to see if your target date falls between.
// Assuming you know d2 > d1
if (targetDt.Ticks > d1.Ticks && targetDt.Ticks < d2.Ticks)
{
// targetDt is in between d1 and d2
}
Do simple compare > and <.
if (dateB < dateA && dateA < dateC)
//do something
If you care only on time:
if (dateA.TimeOfDay>dateB.TimeOfDay && dateA.TimeOfDay<dateC.TimeOfDay)
//do something
Write yourself a Helper function:
public static bool IsBewteenTwoDates(this DateTime dt, DateTime start, DateTime end)
{
return dt >= start && dt <= end;
}
Then call:
.IsBewteenTwoDates(DateTime.Today ,new DateTime(,,));
You can, use:
if (date >= startDate && date<= EndDate) { return true; }
You can use:
if ((DateTime.Compare(dateToCompare, dateIn) == 1) && (DateTime.Compare(dateToCompare, dateOut) == 1)
{
//do code here
}
or
if ((dateToCompare.CompareTo(dateIn) == 1) && (dateToCompare.CompareTo(dateOut) == 1))
{
//do code here
}