Convert datetime to specific format from datatable - c#

I want to convert date time value from datatable to only show time value.
I have below code to make this convert process;
DateTime ST = DateTime.ParseExact(dtPivot.Rows[e.DataRow][0].ToString(), "HH:mm:ss",CultureInfo.InvariantCulture);
ulbTime.Text = ST.ToString("HH:mm:ss");
However this throws an error
String was not recognized as a valid DateTime
I searched however couldn't find a solution for me.
How can I solve this ?

Your question asks how to show it so use String.Format to show the time portion
DateTime ST = Convert.ToDateTime(dtPivot.Rows[e.DataRow][0]);
var t = string.Format("{0:hh:mm}",ST);

You shouldn't need to parse, since the entry being pulled from the database should already be a DateTime field. So in theory, you should be able to pull the data in the following.
var model = IDbConnection.Query(query);
var time = model.First().Date.ToString("hh:mm:ss");
So if you're using a object relational mapper, such as Dapper your model has a DateTime for the object, then you use the string formatter to do the time.
You could also do:
var time = model.First().TimeOfDay();
Built directly into the DateTime is a time of day, works similar to a date short hand method. You could obviously use a DateReader or DataTable accessing the column information index, with a ToString("hh:mm:ss") to return the time specifically. But, you can't do ToString in some instances, because a DBNull.Value or invalid value will cause a reference exception. So you'll need to sanitize and ensure those odd values can't be passed.
I prefer the above, because the mapper should associate the value based on your defined type. So you don't need any extra casting or converting.

Related

Datetime conversion giving error

consider me a beginner in c#
I am doing some changes in a pre developed software (C#.Net) , we are saving data by datewise , Currently in insert query (build in c#) we are passing GETDATE() to save today date , but now we have to save data on the basis of a different date.
When I am building query in c# , I m passing that a datetime variable into query
after conversion , conversion as follow
Date_Stamp = DateTime.ParseExact(dt.Rows[0][0].ToString(), "MM/dd/yyyy HH:mm:ss tt", new CultureInfo("en-IN"));
but it is showing error "String was not recognized as a valid DateTime.".
The reason to convert is coz these date field are getting displayed in format ToString("yyyy-MM-dd"));
Which will give 2017-07-13 14:56:30.233 as 13-jul-2017 on front end (as per requirement). We cant change this part of code as it is being used in lot of places , hard to change .
Problem is
variable storing value as
2017-12-07 00:00:00.000
which give after conversion 07-Dec-2017 [wrong - it is needed as 12-jul-2017]
GETDATE storing value as
2017-07-12 14:56:30.233
which is after conversion coming right as 12-jul-2017
I know there is no datetime format in sql server when it come to storing data
But can we store value from variable [2017-12-07 ] as [2017-07-12 ] ?
How GETDATE() give us date in year-month-date format
?
Neither .NET's nor SQL Server's date related type have any format. All of them are binary values, just like integers and decimals. Formats apply only when they are explicitly or implicitly converted to strings, or parsed from strings.
Assuming your query looked something like SELECT GETDATE(), ... and you loaded the results to an DataTable, the values will be returned as DateTime values. If you used a strongly-typed DataTable you could just use the value. With a generic DataTable the value will be boxed and return as an object.
All you have to do is just cast the field value to DateTime :
Date_Stamp = (DateTime)dt.Rows[0][0];
This will also work for date and datetime2 types. datetimeoffset is returned as DateTimeOffset. time is returned as TimeSpan.
The problem in the original is caused because the field value is formatted into a string using the current culture dt.Rows[0][0].ToString() first. Then ParseExact is called trying to parse it using a different format. A simple DateTime.Parse(dt.Rows[0][0].ToString()) would have worked (even though it would be wasteful), since both DateTime.Parse and DateTime.ToString() use the same culture.
UPDATE
Reading date fields from a table has no issues - the values are returned using the appropriate date type. For example, running SELECT StartDate from ThatTable will return DateTime if the table's schema is :
CREATE TABLE ThatTable
(
ID int,
StartDate datetime
)
Problems are caused if, instead of using the correct type, dates are stored as strings in VARCHAR columns. That's a serious bug that needs to be fixed. There is NO assurance that the strings can be parsed to dates at all, or that they follow the same format. It's all too easy for some faulty application code to use eg DateTime.Now.ToString() and store a localized string in there.
Even if the format is the same, it's just wasteful and unreliable. The string takes more storage than the equivalent type, introduces conversion issues, prevents the use of date functions, and the server can't apply date optimizations to queries and indexing.

Assign a Date variable in SSIS Script Componentt

In my script component, I am trying to assign a value to a Date column (the datatype is DT_DATE). These are DateTime objects in C#, so I thought the following would work:
FooBuffer.Datevar = DateTime.Now;
It compiles, but the line gives an error at runtime:
Error: 0xC020901C at FoobarFlow, OLE DB Destination [77]: There was an error with OLE DB Destination.Inputs[OLE DB Destination Input].Columns[Datevar] on OLE DB Destination.Inputs[OLE DB Destination Input]. The column status returned was: "The value could not be converted because of a potential loss of data.".
My guess is that, since the DateTime class in C# is designed to have precision up to seconds (or even milliseconds -- not sure), and DT_DATE's precision only goes up to days, there would be a possible loss of information.
So the question is, how do I assign such a column's value correctly? Is there any way to convert DateTime object to a Date before assigning it?
Assuming you have a DateTime value in an arbitrarily named variable newDate, try the following:
FooBuffer.DateVar = new DateTime(newDate.Year,
newDate.Month,
newDate.Day,
newDate.Hour,
newDate.Minute,
newDate.Second);
DateTime.Now contains more precision than DT_DATE is capable of storing. Try this instead.
DateTime.Now.Date

Inserting a date into a database does not work (ASPX/C#)

I have this C# code:
string RegisterDate = DateTime.Now.ToString();
RegisterDate = RegisterDate.Remove(10);
RegisterDate = RegisterDate.Replace('/', '-');
RegisterDate = String.Join("-", RegisterDate.Split('-').Reverse());
Which gives thie result: 01-06-2013
The problem is that when I try to insert it to the table I get this result: 21/06/1894
When I get the date via input it works great in the same date format, so why in this case it doesn't work?
update
If I try this:
var RegisterDate = DateTime.Today.Date;
I get Error :
Syntax error (missing operator) in query expression
Wish for help, thanks!
Don't use a string conversion at all. Assuming your data type in the database is DateTime or something similar, just use a parameter and specify its value as the DateTime in your C# code to start with. (I'm assuming you're already using parameterized SQL rather than embedding data straight in your SQL. If you're not using parameters yet, start right away!)
I'd suggest using DateTime.Today to make it clearer that you're only interested in the date part. (Note that this means that the same code running in different places could end up inserting different dates - is that okay? Normally I don't like letting the system local time zone affect things.)
You should generally avoid string conversions unless you really need a string representation of the data. At other times they just cause trouble.
EDIT: You asked for an example. It would be something like:
using (var connection = new SqlConnection(...))
{
connection.Open();
using (var command = new SqlCommand(
"INSERT INTO Foo (Name, RegisterDate) VALUES (#Name, #RegisterDate)",
connection))
{
command.Parameters.Add(new SqlParameter("#Name", SqlDbType.NVarChar))
.Value = name;
// TODO: Consider whether you really want the *local* date, or some
// fixed time zone such as UTC
command.Parameters.Add(new SqlParameter("#RegisterDate", SqlDbType.DateTime))
.Value = DateTime.Today;
command.ExecuteNonQuery();
}
}
Try
string RegisterDate = DateTime.Now.ToString("M-d-yyyy");
and then store in database.
There is no need to manually convert date to different representation. You can go through this Custom Date and Time Format Strings. But, I agree on Jon Skeet's comment below this answer:
If you want to represent a date/time type, use a date/time type. That
way you're able to take advantage of all kinds of things that the
database can do with date/time values, and you'll never get any
non-date/time values in that field.
Note:
DateTime type uses the Gregorian calendar as their default calendar. So, as pointed out by Jon Skeet, this answer won't work with other calenders(Non-Gregorian calendars).

Unable to cast object of type 'System.Object[]' to type 'System.IConvertible' how to deal with this error?

string dt = "SELECT Last_login,SnapNo,Membership from [User] where FB_Id='" + uid1 + "'";
da = new SqlDataAdapter(dt, con);
ds1 = new DataSet();
da.Fill(ds1);
DateTime dt1 = Convert.ToDateTime(ds1.Tables[0].Rows[0].ItemArray);
Int32 snapno = Convert.ToInt32(ds1.Tables[0].Columns["Last_login"]);
string membership = ds1.Tables[0].Rows[2].ItemArray.ToString();
DateTime dt2 = DateTime.Now;
My code is as follows and i am not able to solve this problem
Please help
It's hard to understand what is your code supposed to do and it seems you don't understand what do Rows, Columns, and ItemArray mean. You should probably read their documentation.
What I think you're trying to do is something like this:
var row = ds1.Tables[0].Rows[0];
DateTime lastLogin = (DateTime)row["Last_login"];
Int32 snapno = (Int32)row["snapno"];
string membership = (string)row["membership"]:
"My code is as follows and i am not able to solve this problem": Did you try to use the debugger ? In what line does the exception occur ? This question doesn't really indicate any effort to try to solve the problem your self.
Anyways, with the limited information, I will take a guess at the solution:
ds1.Tables[0].Rows[0].ItemArray is the array of all the items in the row. You can't convert that to a DateTime. It is likely you want:
DateTime dt1 = Convert.ToDateTime(ds1.Tables[0].Rows[0]["Last_login"];
By the way, you really should use parameterized SQL queries.
ItemArray returns an array of objects. DateTime stores a single value. What are you expecting a conversion to do?
If the object array contains dates then you can do this
using system.Linq;
...
DateTime[] dates = ds1.Tables[0].Rows[0].ItemArray.Cast<DateTime>().ToArray();
If you only need one date
DateTime dt1 = (DateTime)ds1.Tables[0].Rows[0]["DateColumn"];
where "DateColumn" is the name of your table column.
DateTime dt1 = Convert.ToDateTime(ds1.Tables[0].Rows[0].ItemArray);
This doesn't really make sense, because the DataRow type's ItemArray property returns an object[] (which should be obvious from the name). You need to get field, for instance as string, before you can do this, like so:
DateTime dt1 = Convert.ToDateTime(ds1.Tables[0].Rows[0]["Last_login"]);
The exception you saw occurs, because all converter methods of the Convert class work with IConvertible objects (i.e. objects whose type implements that interface). Usually only the most primitive types implement this interface, like string, int and DateTime. This is because it often makes sense to convert values of these types into one another.
If you think about it for a moment, you'll realize that there is no such common connection between an object array and the DateTime type, which is why you're getting the exception.
I would like to suggest that first you try to solve the problem on your own before coming here for help. You can learn a lot more that way, which makes you more productive on the long run.
For starters, I recommend that you read the msdn documentation about the IConvertible interface and the Convert class.
Convert.ToDateTime(IConvertible);
IConvertible is an interface anything going inside that function must implement.
An array of objects returned by your SQL call does not implement ICOnvertible, and thus cannot be used as an argument.
Think of it as trying to call a function like so:
private void DoSomething(String input)
by using
DoSomething(999);

Changing the format of DATETIME property in winform C#

What's wrong with this code?
Client c = new Client();
string format = "yyyy/MM/dd HH:mm:ss";
string dateAdded = now.ToString(format);
c.RegistrationDate = DateTime.Parse(dateAdded);
c.RegistrationDate is a dateTime object in the client class and I want it to insert to my database.
However It doesn't convert the freaking date to the format in my mysql database. It always says that string format is incorrect. WHAT have i done wrong???? should I convert my Registration Date to string??? Thanks
**EDIT: Sorry I've forgot to mention. "now" is now = DateTime.Now; it gets the current time of the date and time.
A DateTime doesnt have a format - it's just the date/time. (Whether it's local time, UTC or whatever is a different matter, mind you.)
Firstly, you shouldn't be converting to and from text like you are: that's just a recipe for trouble. Just use:
c.RegistrationDate = now;
... performing any rounding you need to.
You haven't shown how you're trying to insert the value into your database. If you're including the value in the SQL statement directly, that would explain it. You should be using a parameterized SQL statement and passing the value directly in the parameter - no conversion necessary.
If you're already doing that, please show us the code you're trying to use to insert the data, and we'll see what we can do. See the documentation for some examples.
I don't think there is anything wrong with the c# code,except I assume you must be doing
string dateAdded = DateTime.Now.ToString(format);
Otherwise I am not sure what 'now' is.

Categories