Propagate a DateTime column of a DataSet to database - c#

I have a DataSet that has a timestamp (i.e. Datetime.Now ) recording the date and time when a row is added to the DataSet in memory. I will later save (or propagate) all these rows to the SQLCE database where the DataSet's timestamp will be propagate to a DateTime column in the database table.
It works fine and datetime comparison is also ok:
dataView1 = new DataView(
dt,
"DataTime >= '6/9/2011 5:00:20 PM'",
"Data_ID ASC",
DataViewRowState.CurrentRows);
The above code works ok, but I worry if the program runs on different computer (i.e. another language of Windows) the Datetime.Now format would have a different format, or if I compare data that is record from a different computer, the different format of the DateTime in the database will causes it to fail. Would this problem happen? Or is there a safer way of doing this?

String datetime = String.Format("{0:G}", ur_datetime_variable);
will give you string in M/d/yyyy h:mm:ss tt format and then convert the datetime string to DateTime
here's a link http://www.csharp-examples.net/string-format-datetime/ and there's everything bout datetime formating.

Should you not use CultureInvariant
DateTimeFormatInfo.InvariantInfo
when parsing dates

Related

asp.NET and SQL Server datetime issues

I am having hard time to store date information into the datetime column of SQL Server.
I get the input from the user for three columns:
Creation Date
Preparation Date
Next Preparation Date
I use calendarextender and format the date as "yyyy/MM/dd". When all the fields have date, they are stored in the DB as for instance, 16-10-2016 (dd-MM-yyyy).
At this point I have two issues:
These columns are optional, when some of them are empty my code does not work (I assume because datetime cannot be null). To overcome this, I am using the following code snippet but still does not work.
DateTime? creationDate= null;
if (creationDateTextbox.Text != null && creationDateTextbox.Text != "")
{
creationDate= Convert.ToDateTime(creationDateTextbox.Text);
}
When I fetch the dates from DB, they are shown as 10/16/2016 (MM-dd-yyyy) which is different how I formatted it. I would like to show it in the format user enters them.
Dates do not have a format while stored in a database. It is actually usually just a very large long that counts the number of milliseconds from a set starting date.
If you want to store the format you need to stop storing it as dates and instead just treat the text as text in the database, however if you do this you won't get the advantage of sorting or filtering by a date range because it will just be seen as text.
Date time doesn't have any format You can format is as a string, suppose your DateTime type database field dt which contain date as 10/16/2016 (MM-dd-yyyy) then you can convert it
string s = dt.ToString("yyyy/MM/dd");
The answer to one of your questions is here: MSDN
You can use data annotations to format the dates that you get from your SQL DB. I'm assuming that you're using EF6; if not, you can change the field to a varchar in SSMS, and store the date as a String.
And the second, I'm unclear about, but if what you want is for your SQL DB column to be optional, you can use the Optional data annotation for that.

Exception on date format

I have database with column of date type
My computer run on date format MM/dd/yyyy "en-us"
I have grid view which I used to insert data from GV to data base using the
insert SQL command it work fine with out any exception.
When I try to change my computer date format to dd/MM/yyyy
it give my exception when I run my application
("Does not allow to insert data from GV to data base column of date data type")
How can I solve this exception any help please?
Based on your description, it sounds as though you are using inline SQL to write the records to the database. If this is the case, then the correct approach is to format the DateTime in a standard way.
For SQL Server, the standard format is
theDate.ToString("yyyy-MM-dd HH:mm:ss.000")
However, it is strongly recommended to use parameterized SQL instead of inline SQL if possible (there are situations where it is not practical or possible). In this case, the parameters will handle the formatting of the date correctly so you don't have to worry about it.
Try to use DateTime.ParseExact
link to stackoverflow
In your case parsing from string to DB would be look like this
string s = "01/10/2014"; // format dd/MM/yyyy
DateTime dt =
DateTime.ParseExact(s, "dd/MM/yyyy", CultureInfo.InvariantCulture);

Sort DataTable based on date column(dd MMM yyyy)

I have a dataset ds and i need to sort the datatabel of the same ds based on a column and the column name is Date. The values on this column is in 'dd MMM yyyy' format.
If you can't change the column type to Date then try Linq solution as below
var recs = dataset.Tables[0].AsEnumerable()
.OrderBy(x =>DateTime.ParseExact(
x.Field<string>("Date"),
"dd MMM yyyy",
CultureInfo.InvariantCulture));
That's going to be a problem particularly if it's a large table. The best answer of course, would be to redefine the column as a date type. That way it'll sort and join efficiently. If the table is not large, though, you can reformat the date string to ISO format (YYYY-MM-DD), and it will sort correctly. You didn't mention which database you using, and the string and date functions vary among platforms: here's a SQL Server example:
SELECT CAST([Date] AS Date) AS real_date,
my_other_fields
FROM MyTable
I'm at home, so I don't have a SQL Server to test this on right now (I can update the example in the morning if it doesn't work), but that date format is pretty unambiguous to parse, so I expect that the cast will work okay.
If you want to take care of this entirely on the application side, it should be fairly straightforward to write a string function will reorder the year, month and day in the date string.

OleDb return Date Column value with time

I have Excel File(.xls) which contain date column without time value. I am trying to read this file and put it in datatable with connection string as below:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Test\Desktop\1.xls; Extended Properties="Excel 8.0;HDR=YES;IMEX=1;ImportMixedTypes=Text"
Excel File Data
OleDb return datem value with time. 7/20/1995 12:00:00 AM
DataTable Data
But i want datem column value without time. Anyone have idea what i have to do to solve my problem.
Thanks.
.Net framework's DateTime consist of Date and Time. You can't really separate Time part from DateTime, instead you can use custom format for displaying records.
string str = DateTime.Today.ToString("MM/dd/yyyy");
I assume it's just a display issue in the DataSet visualizer. Actually it's a DateTime column which has no inherent format. So if you want to output a DateTime only with the date part:
string date = dt.ToShortDateString(); // or dt.ToString("d")
The Short Date ("d") Format Specifier

C# DateTime Convert from String

I am reading excel file in my C# .net web application and storing that value in Database. Ony of field in Excel is DateTime. I am storing it in string
string tran_time = Convert.ToString(odr[5]); //tran_time is "03-11-2012 16:08:43"
and then convert it in in DateTime and store it in Database (SQL Server 2008)
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime dateVal = DateTime.ParseExact(tran_time, "dd-MM-yyyy HH:mm:ss", culture);
But the Value Being stored in Database is in format
2012-05-11 13:40:23.000 (yyyy-mm-dd)
and the value in Excel is 05-11-2012 13:40:23 (dd-mm-yyyy)
Date & Month is get replaced.
My Question is How can i store it in Database in Format (YYYY-MM-DD HH:MM:SS:FFF)
But the Value Being stored in Database is in format
No it isn't (assuming that you are using a DATETIME column type). This is just what the SQL tools show you.
A DateTime instance, either in a database or in C# does not have an associated format. It only gets formatted when displayed to the user.
Or use yyyy-MM-dd format. Works like a charm:
string myString = dateVal.ToString("yyyy-MM-dd");
Use dd-mm-yyyy instead of dd-MM-yyyy.

Categories

Resources