I have data Table with four columns: Date, isin, Price and State.
I need to get minimum and maximum date from the Date column.
I'm using this code and it works fine with one file however with other file it shows me wrong maximum date.
DateTime stDate = Convert.ToDateTime((excleTable.Compute("min(date)", string.Empty)));
DateTime eDate = Convert.ToDateTime((excleTable.Compute("max(date)", string.Empty)));
For example on first row i have 02/27/2015 and on last row i have 03/31/2015 but it reads only till 03/09/2015 which is incorrect.
Any ideas what should i do ?
Looks like your column type isn't DateTime. If you can fix that than make sure that your DataTable has DateTime type for column date, otherwise you can use LINQ's Max and Min and convert your column to DateTime like:
DateTime stDate = dt.AsEnumerable()
.Max(r => Convert.ToDateTime(r.Field<string>("date")));
DateTime eDate = dt.AsEnumerable()
.Min(r => Convert.ToDateTime(r.Field<string>("date")));
You may have to use DateTime.ParseExact for converting to DateTime, if your string values doesn't correspond to default/available DateTime formats, like:
DateTime stDate = dt.AsEnumerable()
.Max(r => DateTime.ParseExact(r.Field<string>("date"),
"MM/dd/yyyy",
CultureInfo.InvariantCulture));
Related
I have a datetime column in my SQL Server table which contains value like:
2021-01-27 00:00:00.000
When I fetch values from table my DataSet for this certain field is now like
27.1.2021. 0:00:00
I would like to convert this value to another format but what I get is exception
Additional information: String was not recognized as a valid DateTime.
Code:
DateTime dt = DateTime.ParseExact(row["DO_Date"].ToString(), "DD.m.YYYY. H:mm:ss", CultureInfo.InvariantCulture);
Why there is difference between value in table and then later in dataset? How to determine correct format and convert given datetime?
row["DO_Date"].ToString() returns a string which depends on your local system regional datetime setting.
Try doing the following:
DateTime dt = DateTime.ParseExact(row["DO_Date"].ToString("yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
In other words - force the source format to be the same as the one you are trying to convert to.
There is a simpler way though:
DateTime dt = (DateTime)row["DO_Date"]
i have a column on my table "AbsenteeismDate" (type=date) when i want to get rows contain a date it return 0 row.
this is my C# code :
DateTime ClassDate = DateTime.Parse(lblDate.Content.ToString());
var Abs = dbs.GETAbsenteeisms.Where(a => a.AbsenteeismDate == ClassDate ).ToList();
i checked it there is a problem :
"AbsenteeismDate" on database and "ClassDate" aren't equal.
eg.
AbsenteeismDate=1396-05-31
and
ClassDate=1396-05-31 12:00:00 AM
how can i get Date without Time with DateTime type because AbsenteeismDate's type is date on my database.
sorry i can't speak English very well.
A DateTime always has a date and time portion, but if you want to get a DateTime of that date and the time value set to 12:00:00 midnight (00:00:00) use DateTime.Date:
var Abs = dbs.GETAbsenteeisms
.Where(a => a.AbsenteeismDate == ClassDate.Date)
.ToList();
You do just define date time but without the time:
string date = System.DateTime.Now.ToString("yyyy-MM-dd");
Use the Date property:
DateTime ClassDate = DateTime.Parse(lblDate.Content.ToString());
var date = ClassDate.Date;
Otherwise you will have to convert to string as follow
var date=ClassDate.ToString("yyyy-MM-dd");
This works for me:
string a = DateTime.Now.ToShortDateString();
ToShortDateString() converts the value of the current System.DateTime object to equivalent short date string representation. This means the Console output woulf be e.g. 01.01.2017
You can try like this byt setting the date format:
DateTime ClassDate = DateTime.Parse(lblDate.Content.ToString(("yyyy-MM-dd"));
var Abs = dbs.GETAbsenteeisms.Where(a => a.AbsenteeismDate == ClassDate ).ToList();
I have a Datatable with two DateTime columns: date_from and date_to.
string dateFrom = row["date_from"].ToString();
string dateTo = row["date_to"].ToString();
When this code is run in a customer environment, it returns dates in the following format:
"2016-01-01 00.00.00"
"2016-02-01 00.00.00"
This string is then inserted into SQL:
SELECT * FROM my_table
WHERE UPPER(status) = 'N'
AND trans_date >= {ts '1900-01-01 00.00.00' }
AND trans_date <= {ts '1900-01-01 00.00.00' }
When this SQL is executed it returns the error "Conversion failed when converting date and/or time from character string."
So a quick fix for this is to run a string.Replace() where I replace period with colon:
dateFrom = dateFrom.Replace(".", ":");
However, my question is rather why the date is returned with periods as the timestamp separator and not colons?
I have created this test on my local machine, but unfortunately for this scenario it returns a correct representation of the DateTime string:
DataTable table = new DataTable();
table.Columns.Add("date", typeof(DateTime));
DataRow row = table.NewRow();
row["date"] = DateTime.Now;
table.Rows.Add(row);
DateTime date = DateTime.Parse(table.Rows[0]["date"].ToString());
My guess so far would be that it has something to do with the customers culture, but I would really appreciate input from someone who has experience with this so I can give feedback to the customer about why this happened in the first place.
It might just be a coincidence, but it is worth mentioning that this only happens for users with Windows 10. Everyone using Windows 7 does not get this error.
As you says, this is about customer's culture. Specifically CultureInfo.DateTimeFormat.
This property returns a DateTimeFormatInfo object that defines the culturally appropriate format of displaying dates and times.
This object have a property TimeSeparator that gets or sets the string that separates the components of time, that is, the hour, minutes, and seconds.
You can setup this property to specify a separator like :.
However a better approach is passing a specific culture to ToString() method like CultureInfo.InvariantCulture (culture-independent):
string dateFrom = ((DateTime)row["date_from"]).ToString(CultureInfo.InvariantCulture);
string dateTo = ((DateTime)row["date_to"]).ToString(CultureInfo.InvariantCulture);
or use your own format:
string dateFrom = ((DateTime)row["date_from"]).ToString("yyyy-MM-dd HH:mm:ss");
string dateTo = ((DateTime)row["date_to"]).ToString("yyyy-MM-dd HH:mm:ss");
How can I remove time from datetime and store the output in datetime format? I do not want to show the time.
Say I have
string d = "2/27/2013 4:18:53 PM"
How can I store the output in a DateTime variable with only the date and not time.
I can use ToShortDateString() but then it return a string and not datetime.
My ultimate goal is to sort the date column chronologically which can only be done if all the entries are in datetime format and not string.
The Date property of the DateTime struct will give you a date but it will always have a time component that represents midnight ("00:00:00"). If you're starting with a string, you might be able to work with something like this:
DateTime d = DateTime.Parse("2/27/2013 4:18:53 PM").Date; // 2/27/2013 12:00:00 AM
Just make sure you perform your comparison on DateTime objects (i.e. omit all usages of ToString()).
Alternatively, you can format your date in the "sortable" time format:
string d = DateTime.Parse("2/27/2013 4:18:53 PM").ToString("s");
or
string d = yourDateTime.ToString("s");
For the above case d would be 2013-02-27T16:18:53. When sorted alphabetically, the strings will be in chronological order.
DateTime dt = DateTime.now(); (To get Any Date)
string datewithMonth= dt.ToString("MMMM dd, yyyy");
string onlyDate = DateTime.Parse(datewithMonth).ToShortDateString();
Here we get result as 1/1/2014. So that we can perform select operation on sql like this:
searchQuery = "select * from YourTableName where ColumnName = ' " + onlyDate + " ' ";
What about removing the time in culture:-
var submissionDateData = DateTime.Now.ToShortDateString();
var submissionDate = DateTime.Parse(submissionDateData, CultureInfo.CreateSpecificCulture("en-GB"));
First line gives 02/11/2015
Second line gives 11/02/2015 12:00:00 AM
Do you have to do a string split on this or is there a way to get rid of the time?
As easy as this:
d.ToString("mm/dd/yyyy");
DateTime date = DateTime.Parse(d);
I have product list and every product has create date in DateTime type. I want to take some products that created after my entering time in string type.
I enter EnteredDate in string type, like this format : 05/16/2012
1. var dates = from d in Products
2. where d.CreateDate >= DateTime.ParseExact( EnteredDate, "mm/dd/yy", null )
3. select d;
In second line I got error as String was not recognized as a valid DateTime for "mm/dd/yy".
I also tried DateTime.Parse(), Convert.ToDateTime() and got same error.
How can I filter this product list by create date?
"mm" is minutes, and your year is 4 digits, not 2. You want "MM/dd/yyyy", if your format is really always that. How confident are you on that front? (In particular, if it's entered by a user, you should probably make your code culture-sensitive...)
I would suggest pulling the parsing part out of the query though, and also probably using the invariant culture for parsing if you've really got a fixed format:
DateTime date = DateTime.ParseExact(EnteredDate, "MM/dd/yyyy",
CultureInfo.InvariantCulture);
var dates = Products.Where(d => d.CreateDate >= date);
Call
DateTime.ParseExact(EnteredDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);