Calculating dates based on the current date [closed] - c#

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Can any one help me to calculate the past six months,1 year , 2 year dates based on the current date using C#. for example, suppose my current date is 09-11-2012 i need to find out the dates 09-05-2012, 09-05-2010,09-05-2009 etc. I know its a mathematical trick, but i am looking for similar implementation with C#.

Just use the built-in date and calendaring library.
The quick way is to use the DateTime class, but if you want to do things correctly then you'd use the Calendar class, which give you more control over culture-specific information (because Monday is the first day of the week in China, but not in the France).
Anyway:
DateTime currentDate = new DateTime( 2012, 11, 09 ); // assuming 9th November 2012
DateTime sixMonthsAgo = currentDate.AddMonths( -6 );
DateTime yearAgo = currentDate.AddYears( -1 );
DateTime twoYearsAgo = currentDate.AddYears( -2 );
As an aside, please don't write dates in "dd-mm-yyyy" format (neither with slashes or dashes) because it's ambiguous - this site has a large US audience and for some reason 'merkins use "mm/dd/yyyy", which makes no sense to me. The ideal format is "yyyy-MMM-dd" (where "mmm" is the three-letter month name, e.g. "Jan", "Feb", "Mar", etc), or at least in "yyyy-mm-dd" format, which is more compliant with ISO 8601).

Use DateTime
DateTime value = new DateTime(2012, 11, 09);
DateTime nYearsAgo = value.AddYears(-n);

The trick is to use the .AddMonths() or .AddYears() methods on your DateTime object, and supply a negative value to effect a subtraction.

You could take a look at the DateTime Methods, more specifically the AddMonths and AddYears.

Related

Convert DateTime Format with Millisecond in C# [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
This is date time format i want "2013-06-25 18:46:54.687" to pass in to sql server.
How to convert in C#?
DateTime LastUpdateTime=Convert.toDateTime(LastUpdateTime);
//2013-06-25 18:46:54.687 with 3 index of millisecond
sc.Parameters.Add("#LastUpdateTime", SqlDbType.DateTime).Value = LastUpdateTime;
You're using the wrong Data Typ in SQL.
The datetime2 can be considered as an extension of the existing datetime type that has a larger default fractional precision, and optional user-specified precision.
C# Format Milliseconds exactly the way you want.
In an Example:
DateTime date2 = new DateTime(2008, 1, 1, 0, 30, 45, 125);
Console.WriteLine("Date: {0:o}",
date2);
// Displays the following output to the console:
// Date: 2008-01-01T00:30:45.1250000
Look at Why is SQL Server losing a millisecond? and DateTime2 vs DateTime in SQL Server
These are great Question with good Answers, BTW.
If your database query parameter is string, use following format:
LastUpdateTime.ToString("yyyy-MM-dd HH:mm:ss.fff")
Otherwise, it would be better to send datetime as original object,
and let sql server do all conversions.

Going mad with date in SQL and c# [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I am developing a C# application, and I have a date column in SQL Server.
I am performing a query based on date, using DateTimePicker. I have changed the format of datetime picker to short, now it displays date as mm-dd-yyyy
Now while executing I get correct output from date 1-12 but as soon as I select 13 date I get error as
conversion failed when converting date/time from character string
I don't know what is happening!
I suspect you're using the formatted string from that DateTimePicker to build an SQL query on the fly via format strings or concatenation.
Don't do that.
Date/time string literals in SQL tend to use a sane format (i.e. ISO 8601) where the order of the parts differs. The fact that it blows up when you change a piece from 12 to 13 should give it away, actually.
An SqlCommand has parameters (you can insert in the query with #foo. Using those will ensure that everything gets passed in the right way and properly quoted:
using (SqlCommand c = connection.CreateCommand()) {
c.CommandText = "Select roll_number,name from Attendance_table where date=#date";
c.Parameters.AddWithValue("date", dateTimePicker1.Value);
using (var r = c.ExecuteReader()) {
...
}
}
(roughly – you should consult the documentation for proper usage, it's been a while that I wrote such things)

C# converting different String formats to date [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have a WPF window which contains a textbox in which the user can enter a date in any format that he desires and i have to parse it in a datetime variable, simple enough? I tried various formats, some of them work with datatime.parse some don't, so what should i do about such strings?
some e.g. formats (year is not mandatory):
21 Sept
21st Sept
21 September
21st September
21 Sep
21/09
21-09
whatever catches the users fancy as long as it is a proper readable date, can anyone help me with this?
Update : based on comments, i am modifying the input string format....what if user can enter in any way but always day followed by month followed by year(optional).....is that manageable ??
Its not an answer but an Idea:
Why dont you use a Datepicker wo ou spare yourself alot of Job trying to convert every possible date to a valid one, and it looks nice too. Take alook at WPF Toolkit's Calender Datepicker Control
Its futile to do what you are doing.
A user can insert n number ways of adding date. How will you judge what format he has inserted.
Look for calendar controls because calendar is same everywhere and any user no matter where he is will insert correct date in it. In that case you can ask calendar for selecteddate or something kind of property.
There is no good answer to this problem, as best as I can tell.
DateTime.Parse still relies on the date being in a particular format. If you wanted - you could try multiple CultureInfos and hope that one of them works - but that would only work for a tiny subset of written dates real people would find acceptable.
Even if you wrote a lot of code to try and figure out all the possible ways regular people write dates - you'd still have globalization problems - some dates would be valid for interpretation in more than one way.
04/05 <-- What day is that?
Unless this is just for the sake of doing it; I think the best thing to do is simply provide a date-picker control or something similar that makes it easy for the user and gets you the date . Short of that - indicate the date format you expect.
DateTime.Parse works with the current CultureInfo unless you specify another info. Meaning:
21 Sept // invalid
21st Sept // invalid
21 September // acceptable by `en` CultureInfo
21st September // invalid
21 Sep // acceptable by `en` CultureInfo
21/09 // invalid by `en` CultureInfo (09/21 is valid)
21-09 // invalid by `en` CultureInfo (09-21 is valid)
But if you want a nice way for users to input a data consider using a control that will always catch a valid value instead of relying that a user will input the exact information you need manually.

DateTime Format from dd/mm/yyyy format to yyyy-mm-dd [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
how to convert date from dd/mm/yyyy format to yyyy-mm-dd using C#.net. please advice
You are looking for this:
d.ToString("yyyy-MM-dd");
Where d above is a DateTime.
Example:
DateTime d = DateTime.Now;
Console.WriteLine(d.ToString("yyyy-MM-dd"));
Console.WriteLine(d.ToString("dd/MM/yyyy"));
Prints:
2011-12-01
01/12/2011
Probably the most reliable way to do it is to parse your incoming string representing a date:
var date = DateTime.Parse("30/11/2011");
then get the string representation of the returned DateTime object:
var yyyy_mm_dd = date.ToString("yyyy-MM-dd");
yyyy_mm_dd will contain "2011-11-30"
Try doing DateTime.Now.ToString("yyyy-MM-dd");// this will return formatted as string
DateTime.Now.ToString("yyyy-MM-dd");
It's easy, take a look at this. Another way is just to do:
DateTime oldDT = DateTime.Parse("Date in old format"); // And then, later:
DateTime newDT = DateTime.Parse(oldDT.ToString("New format string"));
d.ToString("yyyy-MM-dd")
This will be useful to you.

How to create a variable in C# to hold date? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
Can someone give me the code that has 2 variables. 1 variable holds the date & the other displays in longdate format.
Simple:
DateTime date = DateTime.Now; // will give the date for today
string dateWithFormat = date.ToLongDateString();
You can further modify how the format of the string. You can do this by date.ToString("dd - MM - yyyy"); which would output something like 09 - 15 - 2011
You can read about this here
Use this
DateTime date = DateTime.Now;
string longDate = date.ToLongDateString();
Use this code
DateTime myDate = DateTime.Now;
string longDateString = myDate.ToLongDateString();

Categories