we have a Data-table with 3 fields Date(string type)(MM/dd/YYYY) Hours(string type)(24 hours format) and minutes(string Type) i need to create a another column that of date time based from the above 3 columns and need to sort the data table by that date time column
Date Hours Minutes
5/19/2015 12 30
11/18/2015 23 45
I tried to create a string like this Date +" "+Hours+":"+ Minutes and converted to datetime. But I am getting an error
"String was not recognized as a valid DateTime."
can any help me in this issue please
Why do you store everything as string in the first place? However, you can build the complete DateTime by using DateTime.TryParseExact. Then you can use Linq-To-DataTable for the ordering. Finally create the ordered table with CopyToDataTable:
table.Columns.Add("DateColumn", typeof(DateTime));
foreach (DataRow row in table.Rows)
{
string dateTimeString = String.Format("{0} {1}:{2}",
row.Field<string>("Date"),
row.Field<string>("Hours"),
row.Field<string>("Minutes"));
DateTime date;
if(DateTime.TryParseExact(dateTimeString, "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out date));
{
row.SetField("DateColumn", date);
}
}
table = table.AsEnumerable()
.OrderBy(row => row.Field<DateTime>("DateColumn"))
.CopyToDataTable();
So you don't need to store the hours and minutes separately, a DateTime stores all informations in one object. Three of your columns in the table are redundant.
You need to iterate your DataTable and use DateTime.ParseExact with explicit format string, like that:
DataTable dt;
foreach (var row in dt.Rows)
row["DateTime"]=DateTime.ParseExact(row.Date +" "+row.Hours+":"+ row.Minutes,"MM/dd/yyyy HH:mm",null)
Use ParseExact method. I found it very simple
table.Columns.Add("MixedData",typeof(DateTime));
foreach (DataRow row in table.Rows)
{
DateTime date = DateTime.ParseExact(row["Dates"].ToString() + " " + row["Hours"] + ":" + row["Minutes"], "M/dd/yyyy H:mm", CultureInfo.InvariantCulture);
row["MixedData"] = date;
table.AcceptChanges();
}
Related
I am not able to convert the c# date time7/31/2017 3:13:49 PM to SQL date time while inserting the records to the database.
I am doing this using
DateTime dt = DateTime.Parse("11/23/2010");
string toSqlDate= dt.ToString("yyyy-MM-dd HH:mm:ss");
DateTime finalDate = DateTime.Parse(toSqlDate);
But it's giving me the error.
String was not recognized as a valid DateTime.
The .Net DateTime maps directly to SQL Server DateTime. This means you don't need to worry about the display format at all, since DateTime does not have a display format.
All you need to do is pass the instance of the DateTime struct as a parameter to the SqlCommand:
SqlCommand.Parameters.Add("#DateTimeParam", SqlDbType.DateTime).Value = dt;
Bonus reading: How do I create a parameterized SQL query? Why Should I?
After changing it to year/month/date this can help!
var sqlDate = finalDate.Date.ToString("yyyy-MM-dd HH:mm:ss");
Your dateformat says 'year-month-day' while your date is 'month/day/year', that can't be right. Either change your dateformat or your date's formatting.
This should work:
DateTime dt = DateTime.Parse("2010-11-23 00:00:00");
string toSqlDate= dt.ToString("yyyy-MM-dd HH:mm:ss");
Change query to
insert into table_name (column1) values ('" + dt.Value.ToString("yyyy-MM-dd") + "')
Try the method DateTime.ParseExact and specify The date format that is suitable for you, here is an example from MSDN (https://msdn.microsoft.com/fr-fr/library/w2sa9yss(v=vs.110).aspx) :
var dateString = "06/15/2008";
var format = "d";
try {
var result = DateTime.ParseExact(dateString, format,
CultureInfo.InvariantCulture);
Console.WriteLine("{0} converts to {1}.", dateString,
result.ToString());
}
catch (FormatException)
{
Console.WriteLine("{0} is not in the correct format.", dateString);
}
I'm hoping that there is something I am not seeing clearly, but to simplify, I have the below code
foreach (DataRow row in dt.Rows)
{
row["StartOn"] = Convert.ToDateTime(row["StartOn"].ToString()).ToString("MMM dd").ToString();
}
If I run the below code I get “Aug 09”
Convert.ToDateTime(row["StartOn"].ToString()).ToString("MMM dd").ToString();
If I look to see what is in row[“StartOn”] after this change it contains “8/9/2016 12:00:00 AM”
I'm unable to format my DataRow to an "MMM dd" format
StartOn is apparently a DateTime type. DateTime types do NOT have a format. They are an object that specifies year, month, date, and time (among other things). All you are doing in your conversions is stripping out the time so that the new datetime has a time of 12:00 am.
What is dt.Columns["StartOn"]. I suspect this is DateTime. Let me break down your single line of code into 2 lines.
string s = Convert.ToDateTime(row["StartOn"].ToString()).ToString("MMM dd").ToString();
row["StartOn"] = s;
In line 1, you are converting a DateTime object to a string object. But on line 2, you are implicitly converting your string to a DateTime
var dt = new DataTable();
dt.Columns.Add("StartOn", typeof(DateTime));
dt.Rows.Add(DateTime.Today);
foreach (DataRow row in dt.Rows) {
var data = Convert.ToDateTime(row["StartOn"].ToString()).ToString("MMM dd").ToString();
Console.WriteLine($"Type of stored data is: {data.GetType()}");
row["StartOn"] = data;
}
// fetch the data
var fetchedData = dt.Rows[0][0];
Console.WriteLine($"Type of Fetched Data is: {fetchedData.GetType()}");
BTW, you can use the below line to do the conversion
((DateTime)row["StartOn"]).ToString("MMM dd");
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));
I have a string that represents a time formatted as "HH:mm", say for example "8:15" (assuming the time is in 24 hour format). In C#, How can I convert that into a DateTime instance where the date is today's date and the time is 8:15 AM?
string ds = "8:15";
string[] parts = ds.Split(new[] { ':' });
DateTime dt = new DateTime(
DateTime.Now.Year,
DateTime.Now.Month,
DateTime.Now.Day,
Convert.ToInt32(parts[0]),
Convert.ToInt32(parts[1]));
DateTime.Parse(DateTime.Now.Date.ToString() + " " + yourString);
string time ="8:15";
DateTime date = DateTime.Parse(DateTime.Now.ToString("M/d/yyyy ") + time);
Assuming situation for current date:
string time ="8:15";
var dt = Convert.ToDateTime(String.Format("{0} {1}",
DateTime.Now.ToShortDateString(),time));
If you have a valid date in string then, you can use. Also you can use DateTime.TryParse() to check for a valid date.
var date ="01/01/2014";
var dt = Convert.ToDateTime(String.Format("{0} {1}",
date,time));
You will get output
01/06/2014 08:15:00
You can probably parse the time using TimeSpan.ParseExact and then add it to today's date by
using DateTime.Add.
Given that your time is in a variable like this:
var timeText = "8:15";
Parse the time like this:
var time = TimeSpan.ParseExact(timeText, "h:mm", /*todo*/);
Fill the last argument depending on your requirements.
Then add it to today's date:
DateTime.Today.Add(time);
how can i get the date in this format "30-jun-2013"
at runtime if user type in the above format in the textbox ..it will fetch the matching rows of data for the specified date and filter that and show in datagridview
so for that i want to compare the date format with the text typed in textbox
string todaydate = Convert.ToString(DateTime.Today);
DateTime DTM = Convert.ToDateTime(todaydate);
string datetoday = DTM.ToString("dd-MMM-yyyy");
if (TypeHereTextBox.Text == datetoday)
{
OLCMND2 = new OracleCommand("Select * from TABLENAME where DATE = '" + typeHereTextBox.Text + "'", CON);
OADAP1 = new OracleDataAdapter(OLCMND2);
OADAP1.Fill(DTBLE2);
DatagridView.DataSource = DTBLE2;
}
how can it be solved
hi i got the solution guys
string[] arrayData = TextBox.Text.Split('-');
if (arrayData.Length == 3)
OLCMND2 = new OracleCommand("Select VISITORCOUNT,REMARKS,to_date(to_char(TODAYDATE, 'DD-MON-YYYY'),'DD-MON-YYYY') AS TODAYDATE,CARDNUMBER,PHOTO from VMS_VISITOR where TODAYDATE = TO_DATE('" + TypeHereTextBox.Text + "','dd-MON-yyyy')", CON);
OADAP1 = new OracleDataAdapter(OLCMND2);
OADAP1.Fill(DTBLE2);
DatagridView.DataSource = DTBLE2;
Thanks for all your responses guys
This will parse from that format:
var dateToParse = "30-Jun-2013"; //TypeHereTextBox.Text
var parsedDate = DateTime.ParseExact(dateToParse, "dd-MMM-yyyy", CultureInfo.InvariantCulture);
if (parsedDate.Date == datetoday.Date)
{
// Do stuff
note - June only has 30 days ;)
The best approach would be check for date month and year separately with the today's date. if it matches , then concatenate the date month and year in the format you want and pass to the query.
I would not compare date as strings, fist convert string to DateTime using DateTime.ParseExact by giving datetime format string. then compare two datetime objects instead of string comparison.
And also I would use parameters to set the Date column value as below
OLCMND2 = new OracleCommand("Select * from TABLENAME where DATE = :dateVal", CON);
OLCMND2.Parameters.Add("dateVal", OracleDbType.Date
, myDatetime, System.Data.ParameterDirection.Input);
first of all you are doing string compare, which means you compare the references. please use
if (TypeHereTextBox.Text.Equals(datetoday))
instead.
second, why not comparing dateTime and not strings?
because your data isn't a valid date anyway then you can't use ParseExact or TryParseExact but woth any valid date you can do:
DateTime d;
DateTime.TryParseExact(date, "dd-MMM-yyyy", System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.NoCurrentDateDefault, out d);
if (d== DTM)