Adding months to a DateTime variable - c#

I have a datetime variable with value 12-02-2019 (12th Feb 2019) - this is what i want. But in my code, it is in MM-dd-yyyy format. It saves to db in MM-dd-yyyy format (2nd Dec 2019). When i return it from Datebase, it will be like 02-12-2019 (2nd Dec 2019).
int salesid = (int)dr["SalesID"]; // dr is the datarow
DateTime salesdate = (DateTime)dr["SalesDate"]; // 02-12-2019 (2nd Dec)
And I want to add 4 months to 12-02-2019 (12th Feb). But the runtime adds 4 months to 02-12-2019 (2nd dec) and i am getting 02-04-2020 !!!
DateTime servicedate = salesdate.AddMonths(4); // 2020-12-02
This is wrong. I want to specify the salesdate as 12th Feb 2019 and ii should get 12th June 2019 after adding 4 months to the salesdate.
How this is possible in c# ?

When you save to the DB, make sure you are specify a more verbose format that the DB cannot confuse. For example, if you supply write to the database with myDateTime.Format("dd MMM yyyy"); then it will not confuse the months and days around.
This will make sure that the format in your code, and in you database, all stay aligned.

The problem is in your INSERT statement. While you should be passing the DateTime as-is to your database API, instead of using strings, if you want a simple fix, instead of calling ToString() on your CurrentSaleItem.SaleDate, use a different overload that lets you specify the culture and/or format explicitly, like ToString(string, IFormatProvider)

Related

C# Datatable sorting date DESC

I am displaying a list of items in a data grid binded to dt_pdc. The DueDate column shows the date of the cheque, as day, month and year. When i'm sorting using descending, it does the following:
Date List & Order:
1---4/18/2020
2---4/2/2020
3---4/22/2020
When the day's first digit is less than another day's first digit, it is being sorted first, in the example, 18 april is coming before 2 april, however 22 april comes after 2 april.
Is there anything that i can fix in the sorting view, or do i have to write it in the DB as 02 instead of 2.
dt_pdc.Columns.Add("ID");
dt_pdc.Columns.Add("ChequeNumber");
dt_pdc.Columns.Add("DueDate");
dt_pdc.Columns.Add("Amount");
dt_pdc.Merge(Database.Accounts.Cheques.getPDCChequesSearch(dt_pdc));
dt_pdc.DefaultView.Sort = "DueDate ASC";
or do i have to write it in the DB as 02
no, that's just compounding the error (wait until you get an urgent support call on new year's day if you don't believe me); basically: stop storing dates as strings; store them as dates - i.e. DateTime; then everything will work correctly. If you absolutely must use string for some reason (and it would need to be a good reason), consider using ISO8601 format, i.e. store it as "2020-04-02"; this is then sortable naturally as a string, plus it is unambiguous (there is no question as to whether this is the 2nd of April or the 4th of February).

Is there a specific date format that needs to be inserted in Sqlite db DateTime column?

I'm trying to insert a datetime value into a sqlite table, however the value that's inserted is
"YYYY-01-DD08:01:SS"
{ "NextSyncDate", task.NextSyncDate.ToString("YYYY-MM-DD HH:MM:SS") }
Is there a way to insert am/pm as well in sqlite table's datetime field? Thanks!
This has NOTHING to do with SqlLite and is a basic C# question.
The following is the string you execute to get the timestamp:
.ToString("YYYY-MM-DD HH:MM:SS")
This is totally C#. It also is totally incorrect.
https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
explains all components you can use and guess what - the first one (YYYY) is already not on the list. The C# version is "yyyy" - small. And as some are there in MM and mm (minute and Month) - you basically create garbage.
Hint: next time use debugging. GRAB THE STRING - then it would be obvious that the output of that ToString makes no sense.
Not all letters should be uppercase inside ToString. Try like:
ToString("yyyy-MM-dd HH:mm:ss")
capital MM is month where as lowercase mm is minutes. Capital HH is 24 hours format, where as if you write lowercase hh is 12 hours format

How to convert an internal numeric date to Access Date/Time format?

I get some data from a PICK/UniVerse database that includes dates in a 4 or 5 character numeric format. Here are some examples .. I grabbed the date values from the database, and compared it to the date being shown in an application:
9832 12/1/1994
10027 6/14/1995
10594 1/1/1997
Is it possible to convert these into something that can be put into Access as a Date/Time value?
As A test, I put 9832 in Excel as a General format and then change it to Short Date, it comes up as 12/1/1926. So it's off by exactly 68 years. This was true for 10027 and 10594 as well.
In C# you can use DateTime.FromOADate
DateTime dt = DateTime.FromOADate(41481);
Returns a DateTime equivalent to the specified OLE Automation Date.
That will give you:
dt = {26/07/2013 12:00:00 AM}
Later on you can insert that Date in your Access database.
Access Date/Time values are actually double precision floats. The whole number portion represents the day and the integer portion represents the time of day.
It looks like those Pick date numbers correspond directly to the date portions of Access Date/Time values. So you can use CDate to transform them.
? CDate(41481)
7/26/2013
Experiment some more to get a feel for this:
? Date()
7/26/2013
? CDbl(Date())
41481
Note, although your question is tagged with c#, you don't need that to do these conversions. You can do them with an Access query and ask the db engine to apply those functions.
Since it turned out those date numbers are consistently offset by 68 years, you can still do the conversion in an Access query.
? DateAdd("yyyy", 68, CDate(9832))
12/1/1994
? DateAdd("yyyy", 68, CDate(10027))
6/14/1995
? DateAdd("yyyy", 68, CDate(10594))
1/1/1997
Or ...
? CDate(9832 + CLng(24837))
12/1/1994
? CDate(10027 + CLng(24837))
6/14/1995
? CDate(10594 + CLng(24837))
1/1/1997
A little late to this thread but I'll post some more detail: The Pick / MultiValue DBMS stores dates as an integer with date 0 = 12/31/1967. So as I write this on Jan 16, 2014 the internal Pick date is 16818. If you use the following you'll get that magic number 24837:
DateTime.Parse("12/31/1967").Subtract( DateTime.FromOADate(0)).Days
So add that to your Pick Date to get the OADate.
If you're using any of the common MV DBMS libraries for extracting data (UniObjects, U2.NET, mv.NET ...) you shouldn't need to convert the date like this. A typical function might look like:
string date = OConv( record["PurchaseDate"], "d2/" ); // "01/16/14"
Or rather than extracting the data in the internal DBMS format, you really should be getting it in external format to start. Ask the DBMS developer who provided the data to do this for you. It's real easy on their side to return " date'd2/' " rather than just "date".
Feel free to contact me directly if you need more info in this area.
All multivalue database dates (this includes UniVerse and UniData) are based on a base date of 31st December 1967. You can resolve this to an external data in a number of ways.
The favourite - e.g. if using SQL or one of the internal database tools is to create a data dictionary entry for the field concerned with a date conversion field, For example:
'D2' for a 2-digit year
'D4' for a 4-digit year
'D4/' for a 4-digit year with slash separators
'D4/E' for a 4-digit year with slash separators and explicitly in European format (DD/MM/YYYY) as compared to US format (MM/DD/YYYY).
If no explicit formatting is given then the format will default to environmental settings. There are other formatting options as well and many can be used in combination (as with the above).
As previously advised, the alternative is to adjust the raw date with a formula. The date is in days since 31st December 1967 - The base data for all multivalue databases.

Date Conversion from value in C#

Does anyone possibly recognize the following value "40195.315752" as a date? I need to convert/format this value-based date to a System.DateTime object, but don't understand it's format.
Thanks.
It's a serial date-time, which means it's the number of days since a particular date. Note that you need to know the date which it is an offset to. In Excel, that would be Jan 1st, 1900, which makes your date 17/01/2010 07:34:41, but other programs will vary.
Another common start date is 1st January 1970 (Unix Epoch).
enjoy it:
DateTime.FromOADate(40195.315752).ToLongDateString()
and to convert it to DateTime
DateTime MyDateTime = DateTime.FromOADate(40195.315752);
It means Sunday,January 17 2010
That would possibly be the number of days since a certain date (possibly january 1st 1900), before the decimal point?
the value you have displayed is a double...
var val = 40195.315752;
var span = System.TimeSpan.FromMilliseconds(val);
var time = new DateTime(span.Ticks);
above will convert it to Datetime but besure to note that System.Timespan continas several overloads to load span you need to identify which one is that you want...

How to string year to datetime in sql server

I have a textbox without calendar control and we will call it as publication year(we use diff name in our project). The publication year is 1999, 2001 or 1860.
My step goes like this
I have datetime in my database.(unchangable)
I am using C# and sql server 2005.
string date = textBox1.text;
Datetime dt = Convert.ToDateTime(date);
I pass dt to my database using dynamic sql
to trick the code, I added a prefix 1/1/ before my entered date like 1/1/2010 , it worked well
Now my TL asked me not to do like that.... I am ??? . Please help
It sounds like you should really:
Parse the text as an integer
Create a new DateTime with that year, and January 1st as the day/month.
For example:
int year;
if (int.TryParse(textBox1.Text, out year))
{
DateTime dt = new DateTime(year, 1, 1);
}
else
{
// Handle input
}
As a note, if you only care about the year then I would highly suggest that the database field should be an Int instead of a DateTime.
The minimum sql datetime value is 1/1/1753 for a number of reasons that you can certainly look up. However, the point is that a regular DateTime field is storing way more information than you care about.
So if you deal with publications older than 1753 you're going to run into an architectural issue. And, if somehow you didn't, you'd certainly run into issues deciding if a publication was 280 years old or 279 or 281...
You could use a drop down list with the available years? If there are only three possible publication years, then this would make more sense as an input control. Grab the year and pad the DateTime month and day values with "1" each.

Categories

Resources