Convert DateTime in DataRow to a formatted date string - c#

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");

Related

C# DateTime Field not formatting

I have read numerous help text and tried several different approaches to the problem with no success.
When I simply have the code line.Cells[5].Value = vo2.Rows[0]["Start"].toString(); I get 3/9/2019 8:00:00 as the result in the datagridview. I want this to be dd/mm/yyyy format.
How can I achieve this?
SmartsheetDataAdapter dataAdapter4 = new SmartsheetDataAdapter(sql10, connection);
DataTable vo2 = new DataTable();
dataAdapter4.Fill(vo2);
//double vocost = 0;
if (vo2.Rows.Count > 0)
{
DateTime thisdate = new DateTime(vo2.Rows[0]["Start"]);
//DateTime deldate = DateTime.ParseExact(dd1, "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
line.Cells[5].Value = thisdate.ToString("dd/M/yyyy");
Current code gives an error:
Argument 1: cannot convert from 'object' to 'long'
You get the error because the DateTime constructor takes a long but you pass an object:
DateTime thisdate = new DateTime(vo2.Rows[0]["Start"]);
I guess that the first column in the DataTable is already aDateTime, then use this:
DateTime thisdate = vo2.Rows[0].Field<DateTime>("Start");
Otherwise you have to parse it, for example:
string dtVal = vo2.Rows[0]["Start"].ToString(); // 3/9/2019 8:00:00
DateTime thisdate = DateTime.ParseExact(dtVal, "d'/'M'/'yyyy h:mm:ss", null);
or even simpler, because with this input you don't need ParseExact but you can use Parse:
DateTime thisdate = DateTime.Parse(dtVal);
You should Convert the value read (note, that vo2.Rows[0]["Start"] is of type object when you want DateTime):
DateTime thisdate = Convert.ToDateTime(vo2.Rows[0]["Start"]);
// MM - if you want leading zero; note, that "mm" stands for minutes
line.Cells[5].Value = thisdate.ToString("dd/MM/yyyy");
Explanation of what's going on:
vo2.Rows[0]["Start" is of type object
new DateTime(long ticks) wants single long argument
The compiler complains of the argument's type given (if you call the constructor with one it must be of type long)

DateTime.Parse() -- String was not recognized as a valid DateTime

I am trying to consume an object returned by a third party .dll
public class AuroraTransaction
{
....
public DateTime Date { get; }
....
}
I'm having trouble with that Date property:
// Gets a List from the third party .dll...
List<AuroraTransaction> transactions = report.RunReport();
Then:
foreach (AuroraTransaction trans in transactions)
{
....
// This next line throws an error...
DateTime dt = DateTime.Parse(trans.Date.ToString(), CultureInfo.InvariantCulture);
....
}
String was not recognized as a valid DateTime.
If I put trans.Date.ToString() in the watch....
I'm stumped as to why I'm getting the error
I'm pretty sure what you are trying to achieve here is not possible from what you are trying to do, like Mohammad Wasim said, it would be better to parse it then define the year, month, day, hour,minute,second.
DateTime dt = DateTime.Parse(trans.Date.ToString("yyyy/MM/dd HH:mm:ss"), CultureInfo.InvariantCulture);
try like this
DateTime dt = DateTime.Parse(trans.Date.ToString("yyyy/MM/dd HH:mm:ss"), CultureInfo.InvariantCulture);

InvalidCastException convert string to DateTime

Basically trying to read in a file and change it from 7 columns to 5 columns and to change the date format as well. Should add that I'm using linqpad and the language is C# statements.
Code:
string txtFolderPath = #"D:\Testing\BM\";
string[] files = Directory.GetFiles(txtFolderPath, "cplt.csv", SearchOption.AllDirectories);
//files.Dump();
foreach (string file in files)
{
// reading in csv file
var csvData = from row in new CpltData(#file, 1000000, 1000000, "")
//#"C:\Miu\Blue Fin III - A\Blue Fin III - A\cplt.csv"
select new
{
Period = row.Period,
IndexEltId = row.IndexEltId,
EventId = row.EventId,
Date = row.Date.ToString("dd-MMM-yyyy HH.mm.ss"),
Payout = row.Payout
};
//csvData.Dump();
Util.WriteCsv(csvData, #file);
}
Error message: InvalidCastException Couldn't convert value '8/22/2015
1:19:01 AM' to DateTime in row 2
Error occurs on the following line:
var csvData = from row in new CpltData(#file, 1000000, 1000000, "")
CpltData(string csvFilePath, int noOfPeriods, double principal, string currency)
It's being imported from some dll, not sure how to access it :/
The error message is pretty clear: you are taking a perfectly fine DateTime variable, converting it to string, and then you are trying to assign that string to another DateTime variable. That does not compute.
There is no such thing as a "date format" in a DateTime variable.
A DateTime just holds a date, in an internal representation which has absolutely nothing to do with any notion that you might have of years, months, etc. The "date format" is something that you use when displaying the DateTime.
So, just assign your row.Date to your Date and you are done with this piece of code.
Later, when it is time to display that Date, then apply a "date format".

Conversion of date string and time string into datetime in c#

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();
}

Reading Datetime value From Excel sheet

when am trying to read datetime type value from excel sheet it is returning a double value.for example if want to read value '2007-02-19 14:11:45.730' like this, i am getting a double type value .further i am converting this double value using timespan,but not complete successfully because i am getting only this value '2007-02-19 12:00:00 AM'
now i want exact same datetime value as first one. My code is like :-
TimeSpan datefromexcel = new TimeSpan(Convert.ToInt32((range.Cells[rCnt, cCnt] as Excel.Range).Value2), 0, 0, 0);
DateTime inputdate = new DateTime(1900, 1, 1).Add(datefromexcel);
arrrow2[cCnt - 1] = inputdate.ToString();
Please help!!!
Thanks.
You need to convert the date format from OLE Automation to the .net format by using DateTime.FromOADate.
double d = double.Parse(b);
DateTime conv = DateTime.FromOADate(d);
Perhaps you could try using the DateTime.FromOADate method to convert between Excel and .net.
Reading Datetime value From Excel sheet : Try this will be work.
string sDate = (xlRange.Cells[4, 3] as Excel.Range).Value2.ToString();
double date = double.Parse(sDate);
var dateTime = DateTime.FromOADate(date).ToString("MMMM dd, yyyy");
Alternatively, if your cell is already a real date, just use .Value instead of .Value2:
excelApp.Range[namedRange].Value
{21/02/2013 00:00:00}
Date: {21/02/2013 00:00:00}
Day: 21
DayOfWeek: Thursday
DayOfYear: 52
Hour: 0
Kind: Unspecified
Millisecond: 0
Minute: 0
Month: 2
Second: 0
Ticks: 634970016000000000
TimeOfDay: {00:00:00}
Year: 2013
excelApp.Range[namedRange].Value2
41326.0
Or you can simply use OleDbDataAdapter to get data from Excel
i had a similar situation and i used the below code for getting this worked..
Aspose.Cells.LoadOptions loadOptions = new Aspose.Cells.LoadOptions(Aspose.Cells.LoadFormat.CSV);
Workbook workbook = new Workbook(fstream, loadOptions);
Worksheet worksheet = workbook.Worksheets[0];
dt = worksheet.Cells.ExportDataTable(0, 0, worksheet.Cells.MaxDisplayRange.RowCount, worksheet.Cells.MaxDisplayRange.ColumnCount, true);
DataTable dtCloned = dt.Clone();
ArrayList myAL = new ArrayList();
foreach (DataColumn column in dtCloned.Columns)
{
if (column.DataType == Type.GetType("System.DateTime"))
{
column.DataType = typeof(String);
myAL.Add(column.ColumnName);
}
}
foreach (DataRow row in dt.Rows)
{
dtCloned.ImportRow(row);
}
foreach (string colName in myAL)
{
dtCloned.Columns[colName].Convert(val => DateTime.Parse(Convert.ToString(val)).ToString("MMMM dd, yyyy"));
}
/*******************************/
public static class MyExtension
{
public static void Convert<T>(this DataColumn column, Func<object, T> conversion)
{
foreach (DataRow row in column.Table.Rows)
{
row[column] = conversion(row[column]);
}
}
}
Hope this helps some1
thx_joxin
You may want to try out simple function I posted on another thread related to reading date value from excel sheet.
It simply takes text from the cell as input and gives DateTime as output.
I would be happy to see improvement in my sample code provided for benefit of the .Net development community.
Here is the link for the thread C# not reading excel date from spreadsheet
Another option: when cell type is unknown at compile time and cell is formatted as Date Range.Value returns a desired DateTime object.
public static DateTime? GetAsDateTimeOrDefault(Range cell)
{
object cellValue = cell.Value;
if (cellValue is DateTime result)
{
return result;
}
return null;
}

Categories

Resources