I have been trying to set a time limit for a certain form to not function past a specified date in a month, but I have been unsuccessful so far.
I am working with a low-code windows interface software that does the majority of the actual coding in the background but since it has some limitations I need to code this Date limit in myself.
The best thing I reached after looking around was this:
DateTime temp = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 15);
And I would add a rule in the program that the date shouldn't be higher than the above.
But for some reason it doesn't work giving me an "; expected" error (in line 1 char 29).
This will only open the specified form up to and including the 15th of the month:
if (DateTime.Now.Day <= 15)
{
myForm.Show();
}
You can obviously change the operator and/or value to change the way it works. The important point is the Day property of the DateTime value representing the current date.
you can use the below code. you have to use AddDays method.
DateTime now = DateTime.Now;
DateTime pastTime = now.AddDays(-15);
DateTime futureTime = now.AddDays(15);
It will give you backdate if you provide a negative value.
you also have a typo in your code, the correct DataType is DateTime.
you can comparisons as you have for int, and doubles.
if(now < pastTime)
{
}
The Error:
"; expected" error (in line 1 char 29).
You're missing a ending semi-colon, probably in a line above or below.
Tip: try to name variables well with meaning especially in anything-but-code (ABC) environments:
DateTime avoidReservedKeyWords = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 15);
Related
I have the following code in my C# program.
DateTime dateForButton = DateTime.Now;
dateForButton = dateForButton.AddDays(-1); // ERROR: un-representable DateTime
Whenever I run it, I get the following error:
The added or subtracted value results in an un-representable DateTime.
Parameter name: value
Iv'e never seen this error message before, and don't understand why I'm seeing it. From the answers Iv'e read so far, I'm lead to believe that I can use -1 in an add operation to subtract days, but as my question shows this is not the case for what I'm attempting to do.
DateTime dateForButton = DateTime.Now.AddDays(-1);
That error usually occurs when you try to subtract an interval from DateTime.MinValue or you want to add something to DateTime.MaxValue (or you try to instantiate a date outside this min-max interval). Are you sure you're not assigning MinValue somewhere?
You can do:
DateTime.Today.AddDays(-1)
You can use the following code:
dateForButton = dateForButton.Subtract(TimeSpan.FromDays(1));
The dateTime.AddDays(-1) does not subtract that one day from the dateTime reference. It will return a new instance, with that one day subtracted from the original reference.
DateTime dateTime = DateTime.Now;
DateTime otherDateTime = dateTime.AddDays(-1);
Instead of directly decreasing number of days from the date object directly, first get date value then subtract days. See below example:
DateTime SevenDaysFromEndDate = someDate.Value.AddDays(-1);
Here, someDate is a variable of type DateTime.
The object (i.e. destination variable) for the AddDays method can't be the same as the source.
Instead of:
DateTime today = DateTime.Today;
today.AddDays(-7);
Try this instead:
DateTime today = DateTime.Today;
DateTime sevenDaysEarlier = today.AddDays(-7);
I've had issues using AddDays(-1).
My solution is TimeSpan.
DateTime.Now - TimeSpan.FromDays(1);
Using AddDays(-1) worked for me until I tried to cross months. When I tried to subtract 2 days from 2017-01-01 the result was 2016-00-30. It could not handle the month change correctly (though the year seemed to be fine).
I used date = Convert.ToDateTime(date).Subtract(TimeSpan.FromDays(2)).ToString("yyyy-mm-dd");
and have no issues.
I'm trying to find the time between two dates, one being the current day (Today) and the other, a user defined deadline.
I'm working with C# Windows Forms and I've used a "date time picker" so that the user can choose a deadline date and I've created a string called Today and used
string Today = System.DateTime.Today.ToString("dd-mm-yyyy");
as the current date. But I don't know how to find the length of time between these two points (since they're strings), my program is a simple "to do list" where task duration's are in days and weeks (the "yyyy" is just for aesthetic purposes, it can be removed if necessary).
I've had a look over the internet and all I can seem to find is how to do this with "DateTime"s, instead of strings (or am I missing something?).
Any help would be greatly apreciated.
Use the 'Value' property of your DateTimePicker to get the DateTime value and use DateTime.Now to get the DateTime value for the current time (in the local timezone).
If you are only subtracting dates (with no time component), access the Date property of both DateTime objects before subtracting.
DateTime userDate = dateTimePicker.Value.Date;
DateTime currentDate = DateTime.Now.Date;
TimeSpan difference = userDate.Subtract(currentDate); //assuming deadline is in the future
Don't use two strings - use the actual DateTime instances. Strings don't and can't "understand" dates - that's why the DateTime object exists.
When you subtract two dates from each other, you get a TimeSpan instance. This gives you the amount of time difference.
TimeSpan difference = date1 - date2;
I guess the following you are looking for:
Date1.Subtract(Date2).TotalTime
Following link will help you understand more
http://www.c-sharpcorner.com/UploadFile/DipalChoksi/DateDiff_CS_DC09132006172429PM/DateDiff_CS_DC.aspx
AS Oded mentions the string is not the best approach. DateTimes cann be substracted from one another and give you a TimeSpan that represents, well, that, a time span.
Here is an MSDN example that should clarify things.
DateTime departure = new DateTime(2010, 6, 12, 18, 32, 0);
DateTime arrival = new DateTime(2010, 6, 13, 22, 47, 0);
TimeSpan travelTime = arrival - departure;
Console.WriteLine("{0} - {1} = {2}", arrival, departure, travelTime);
// The example displays the following output:
// 6/13/2010 10:47:00 PM - 6/12/2010 6:32:00 PM = 1.04:15:00
I have a code in vb, and I'm trying convert it to c#.
_nextContactDate.ToShortDateString > New Date(1900, 1, 1)
This is _nexContractDate declaration:
Private _nextContactDate As DateTime
It's weird for me. Comapre datetime to string?
What this code is doing is extracting the date part (i.e. removing the time part) and using VB's loose nature to allow a date represented as a string to be implicitly converted back to a date for the purposes of comparison with an actual date.
The correct way to remove the time part would be to check as follows:
_nextContactDate.Date > new DateTime(1900, 1, 1)
It seems odd, as this means that the 1st Jan 1900 will fail this check, and only dates from the 2nd Jan 1900 will pass. As such, I'd be inclined to check whether this code has a logic error.
I'm not sure I understand your question entirely, but why compare a DateTime to a string anyway, why not just compare dates?
if (_nextContactDate > new DateTime(1900, 1, 1))
{
}
As noted by Greg, currently the ToShortDateString removes some parts of the date (specifically, the time units), but upon comparison with a minimum date as such, this is rather redundant - if you are concerned at such a level, then you can compare only the Date members.
no, you don't need to compare DataTime variable in string format.
you can compare like below:
DateTime myDate = new DateTime(2011,8,24);
if(myDate > DateTime.MinValue)
DoSomething();
In many databases, time is stored as the minimum date + the time value.
So assuming the minimum date is 31 Dec 1899 2359H (if I reckon right, that's the minimum for Access) then 1300H will be stored as 01 Jan 1900 1300H.
Dates are stored as 'usual'. And dates with time components have the date value with the time component attached to them.
What's this got to do with the code? The original programmer is trying to determine whether the field is holding a date or a time value. The analogy is simple. If the value is time only, then by stripping off the time component, you'll be left with 01 Jan 1900. If it contains a date component, it's going to be more than 01 Jan 1900.
Is there an elegant way to be permissive in date input in C# to accommodate user input like '2009-09-31' (e.g. September 31, which doesn't exist and causes DateTime.Parse to choke)? Ideally I would like to parse this as October 1 (e.g. latest possible date plus overflow).
I don't believe this is handled directly for you. What you could do is parse the date yourself, as three separate integers:
Parse the 2009, and construct a DateTime of 1st January 2009
Parse the 09 and subtract one, then call dt = dt.AddMonths(8) to get September 1st
Parse the 31 and subtract one, then call dt.AddDays(30)
This will handle things like 2009/13/01 to mean 1st January 2010. It won't do what you want with February 31st though, I suspect...
One way to avoid incorrect dates in User input, is not to let them happen in the first instance, i.e. use a date picker control.
What about using DateTime.TryParse ?
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.
This MSDN page shows examples of usage.
I think the DateTime.DaysInMonth method can help a lot, after a TryParse ... you can implement the logic you are talking about
You should (morally) not try to handle inputs like this. Is February 29, 1900 to be interpreted as March 1, 1900 (because February 29, 1900 could be interpreted as the day after February 28, 1900 but since it doesn't exist move the actual day after February 28, 1900) or as February 28, 1900 (because February 29, 1900 could be interpreted as the last day of February, 1900)? Another situation is what if the user means to type "2009-3-3" but because of fast and sticky fingers accidentally types "2009-3-33". Then rather than their error being caught, a custom parser will swallow this into, say, 4/2/2009. Because of situations like this, you should just DateTime.TryParse the input and inform the user if invalid input occurs. That's what you should do.
Now, if it's a requirement that you handle such input. I would use something along the lines of the following:
static DateTime Parse(int year, int month, int day) {
DateTime date;
if (month < 1 || month > 12) {
int direction = month < 1 ? 1 : -1;
do {
month += direction * 12;
year -= direction;
} while (month < 1 || month > 12);
}
int daysInMonth = DateTime.DaysInMonth(year, month);
if (day < 1 || day > daysInMonth) {
date = new DateTime(year, month, daysInMonth);
int difference = day - daysInMonth;
date = date.AddDays(difference);
}
else {
date = new DateTime(year, month, day);
}
return date;
}
The compiler will just throw a cannot parse exception, so you'll have to write your own parser for this kind of problems.
Rule #1: As reasonably as possible, don't allow a user to input invalid data in the first place.
If you're doing Windows Forms, use the DateTimePicker as much as possible (although it has its limitations when it comes to locale); or, if your app is in ASP.NET, use a Calendar, or one of the AJAX Control Toolkit controls (I forget the exact name right now), but it does a little popup with a calendar.
I would strongly advise against separating out the date components into different fields (or parsing them as such) if there is ANY chance of needing to localize this application later.
My credit card processor requires I send a two-digit year from the credit card expiration date. Here is how I am currently processing:
I put a DropDownList of the 4-digit year on the page.
I validate the expiration date in a DateTime field to be sure that the expiration date being passed to the CC processor isn't expired.
I send a two-digit year to the CC processor (as required). I do this via a substring of the value from the year DDL.
Is there a method out there to convert a four-digit year to a two-digit year. I am not seeing anything on the DateTime object. Or should I just keep processing it as I am?
If you're creating a DateTime object using the expiration dates (month/year), you can use ToString() on your DateTime variable like so:
DateTime expirationDate = new DateTime(2008, 1, 31); // random date
string lastTwoDigitsOfYear = expirationDate.ToString("yy");
Edit: Be careful with your dates though if you use the DateTime object during validation. If somebody selects 05/2008 as their card's expiration date, it expires at the end of May, not on the first.
1st solution (fastest) :
yourDateTime.Year % 100
2nd solution (more elegant in my opinion) :
yourDateTime.ToString("yy")
The answer is already given. But here I want to add something.
Some person told that it did not work.
May be you are using
DateTime.Now.Year.ToString("yy");
that is why it is not working. I also made the same the mistake.
Change it to
DateTime.Now.ToString("yy");
This should work for you:
public int Get4LetterYear(int twoLetterYear)
{
int firstTwoDigits =
Convert.ToInt32(DateTime.Now.Year.ToString().Substring(2, 2));
return Get4LetterYear(twoLetterYear, firstTwoDigits);
}
public int Get4LetterYear(int twoLetterYear, int firstTwoDigits)
{
return Convert.ToInt32(firstTwoDigits.ToString() + twoLetterYear.ToString());
}
public int Get2LetterYear(int fourLetterYear)
{
return Convert.ToInt32(fourLetterYear.ToString().Substring(2, 2));
}
I don't think there are any special built-in stuff in .NET.
Update: It's missing some validation that you maybe should do. Validate length of inputted variables, and so on.
Use the DateTime object ToString with a custom format string like myDate.ToString("MM/dd/yy") for example.
//using java script
var curDate = new Date();
var curYear = curDate.getFullYear();
curYear = curYear.toString().slice(2);
document.write(curYear)
//using java script
//using sqlserver
select Right(Year(getDate()),2)
//using sql server
//Using c#.net
DateTime dt = DateTime.Now;
string curYear = dt.Year.ToString().Substring(2,2).ToString() ;
//using c#.net
Starting with c# 6.0 you can use the built-in composite formatting in string interpolation on anything that processes c#, like an MVC Razor page.
DateTime date = DateTime.Now;
string myTwoDigitYear = $"{date:yy};
No extensions necessary. You can use most of the standard date and time format strings after the colon after any valid DateTime object inside the curly brackets to use the built-in composite formatting.
At this point, the simplest way is to just truncate the last two digits of the year. For credit cards, having a date in the past is unnecessary so Y2K has no meaning. The same applies for if somehow your code is still running in 90+ years.
I'd go further and say that instead of using a drop down list, let the user type in the year themselves. This is a common way of doing it and most users can handle it.
I've seen some systems decide that the cutoff is 75; 75+ is 19xx and below is 20xx.
DateTime.Now.Year - (DateTime.Now.Year / 100 * 100)
Works for current year. Change DateTime.Now.Year to make it work also for another year.
The answer is quite simple:
DateTime Today = DateTime.Today;
string zeroBased = Today.ToString("yy-MM-dd");
Why not have the original drop down on the page be a 2 digit value only? Credit cards only cover a small span when looking at the year especially if the CC vendor only takes in 2 digits already.
Here is a link to a 4Guys article on how you can format Dates and Times using the ToString() method by passing in a custom format string.
http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=181
Just in case it goes away here is one of the examples.
'Create a var. named rightNow and set it to the current date/time
Dim rightNow as DateTime = DateTime.Now
Dim s as String 'create a string
s = rightNow.ToString("MMM dd, yyyy")
Since his link is broken here is a link to the DateTimeFormatInfo class that makes those formatting options possible.
http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx
It's probably a little more consistent to do something like that rather than use a substring, but who knows.
This is an old post, but I thought I'd give an example using an ExtensionMethod (since C# 3.0), since this will hide the implementation and allow for use everywhere in the project instead or recreating the code over and over or needing to be aware of some utility class.
Extension methods enable you to "add" methods to existing types
without creating a new derived type, recompiling, or otherwise
modifying the original type. Extension methods are a special kind of
static method, but they are called as if they were instance methods on
the extended type. For client code written in C# and Visual Basic,
there is no apparent difference between calling an extension method
and the methods that are actually defined in a type.
public static class DateTimeExtensions
{
public static int ToYearLastTwoDigit(this DateTime date)
{
var temp = date.ToString("yy");
return int.Parse(temp);
}
}
You can then call this method anywhere you use a DateTime object, for example...
var dateTime = new DateTime(2015, 06, 19);
var year = cob.ToYearLastTwoDigit();
This seems to work okay for me.
yourDateTime.ToString().Substring(2);
Even if a builtin way existed, it wouldn't validate it as greater than today and it would differ very little from a substring call. I wouldn't worry about it.