InvalidCastException convert string to DateTime - c#

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".

Related

Converting a SAS Datetime value to datetime string in a Datatable using C#

I am working on an application that deals with loading some SAS datasets into SQL using C#. I use the SAS OLE DB Adapter to load the SAS dataset into C# data table and its working. However, the datevalues which is stored as string datatype in the SAS file is getting loaded as 10 digit number and stored as string format in the data table.
Hence, I tried to convert them to datetime however I am getting only the date value and time value is 00:00:00 for all the records. The source has the date and time values for each record. Below is my code that I use to convert the string to datetime string.
public string ComputeDate(string sSourceData)
{
string sProcessedDate = string.Empty;
int iDateValue = ((Convert.ToInt32(sSourceData) / 86400) + 21916);
Double dDate = Convert.ToInt32(iDateValue);
DateTime dtDateValue = DateTime.FromOADate(dDate);
sProcessedDate = dtDateValue.ToString();
return sProcessedDate;
}
The source data sample and the data that is getting loaded in the data table is below
The output after converting the OADate is below
It would be great if someone can help me out in providing me an solution for getting the output along with original time value provided in the source.
Thanks in advance.
Integer ratios such as
Convert.ToInt32(sSourceData) / 86400
will yield an integer.
Ensure the result contains the day fraction ([0..1]) which is the time part in SQL / C#
Double dDate = Convert.ToInt32(sSourceData) / 86400.0 + 21916.0;
Found the solution for my problem.
Instead of setting the datatype as Int, I need to set the datatype as double so that the timestamp of the OADate will be coming as decmimal values.
This way its getting output as datetime.
public string ComputeDate(string sSourceData)
{
string sProcessedDate = string.Empty;
Double iDateValue = ((Convert.ToDouble(sSourceData) / 86400) + 21916);
DateTime dtDateValue = DateTime.FromOADate(iDateValue);
sProcessedDate = dtDateValue.ToString();
return sProcessedDate;
}

Input string was not in a correct format while reading date from excel

I am trying to upload an excel sheet. Now I am getting an error for the date column. I was able to fix it up to this point base on some suggestions here. This is the date format on the excel 20/4/2020
But I couldn't figure it out from this point. I kept getting. I was able to get the Value from the excel sheet and stored in string date
Input string was not in a correct format.
at System.Number.ThrowOverflowOrFormatException(ParsingStatus status,
TypeCode type) at System.Double.Parse(String s)
Here is my code below
//be on the first column [r,c]
int row = 2;
for (int i = 2; i <= noOfRow; i++) //start from the second row
{
if (!string.IsNullOrEmpty(workSheet.Cells[i, 3].Text))
{
string date = workSheet.Cells[i, 3].Value.ToString();
try
{
double d = double.Parse(date);//Error is coming from here
DateTime conv = DateTime.FromOADate(d);
}
catch (Exception ex)
{}
}
}
I will appreciate if someone can help me out
Thanks
The problem occurs because value in the variable date = "11/5/2020" is not a double value. It is a DateTime value. To fix you problem you should use the next code to convert value in the date variable into DateTime value:
DateTime d = DateTime.ParseExact(date, "d/M/yyyy", CultureInfo.InvariantCulture);
Method DateTime.ParseExact allows you to set the format of the parsed date.
The above code worked for me the day you shared with me. But now I am
getting this error {"String '6/3/2020 12:00:00 AM' was not recognized
as a valid DateTime."} I have tried implementing almost everything on
stackoverflow.
If date string in your excel file can be in different formats, then you can use overload of the method DateTime.ParseExact that supports specifying several parse formats. For example:
string[] formats = {"d/M/yyyy", "d/M/yyyy hh:mm:ss tt"};
DateTime d = DateTime.ParseExact(date, formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
Here is complete sample that demostrates this overload of the method DateTime.ParseExact.

How to get the desired output by modifying string after removing / from string

I have a string like this:
30/04/2018 o/p=300418
01/03/2017 o/p=010317
10/11/2018 o/p=101118
12/11/2123 o/p=121123
1/1/2018 o/p =010118
code tried but can't get the last one 1/1/2018
string a = "31/04/2018";
string b = a.Replace("/","");
b = b.Remove(4, 2);
You should parse to a DateTime and then use the ToString to go back to a string. The following works with your given input.
var dateStrings = new []{"30/04/2018", "01/03/2017","10/11/2018","12/11/2123","1/1/2018"};
foreach(var ds in dateStrings)
{
Console.WriteLine(DateTime.ParseExact(ds, "d/M/yyyy", System.Globalization.CultureInfo.InvariantCulture).ToString("ddMMyy"));
}
The only change I made is to the first date as that is not a valid date within that month (April has 30 days, not 31). If that is going to be a problem then you should change it to TryParse instead, currently I assumed your example was faulty and not your actual data.
Your structure varies, all of the examples above use two digit month and day, while the bottom only uses a single digit month and day. Your current code basically will replace the slash with an empty string, but when you remove index four to two your output would deviate.
The simplest approach would be:
var date = DateTime.Parse("...");
var filter = $"o/p = {date:MMddyyyy}";
Obviously you may have to validate and ensure accuracy of your date conversion, but I don't know how your applications works.
If you can reasonably expect that the passed in dates are actual dates (hint: there are only 30 days in April) you should make a function that parses the string into DateTimes, then uses string formats to get the output how you want:
public static string ToDateTimeFormat(string input)
{
DateTime output;
if(DateTime.TryParse(input, out output))
{
return output.ToString("MMddyy");
}
return input; //parse fails, return original input
}
My example will still take "bad" dates, but it will not throw an exception like some of the other answers given here (TryParse() vs Parse()).
There is obviously a small bit of overhead with parsing but its negligible compared to all the logic you would need to get the proper string manipulation.
Fiddle here
Parse the string as DateTime. Then run ToString with the format you desire.
var a = "1/1/2018";
var date = DateTime.Parse(a);
var result = date.ToString("ddMMyyyy");
You can use ParseExact to parse the input, then use ToString to format the output.
For example:
private static void Main()
{
var testData = new List<string>
{
"31/04/2018",
"01/03/2017",
"10/11/2018",
"12/11/2123",
"1/1/2018",
};
foreach (var data in testData)
{
Console.WriteLine(DateTime.ParseExact(data, "d/m/yyyy", null).ToString("ddmmyy"));
}
GetKeyFromUser("\nDone! Press any key to exit...");
}
Output
You didn't specify whether these are DateTime values or just strings that look like date time values. I'll assume these are DateTime values.
Convert the string to a DateTime. Then use a string formatter. It's important to specify the culture. In this case dd/mm/yyyy is common in the UK.
var culture = new CultureInfo("en-GB");//UK uses the datetime format dd/MM/yyyy
var dates = new List<string>{"30/04/2018", "01/03/2017","10/11/2018","12/11/2123","1/1/2018"};
foreach (var date in dates)
{
//TODO: Do something with these values
DateTime.Parse(date, culture).ToString("ddMMyyyy");
}
Otherwise, running DateTime.Parse on a machine with a different culture could result in a FormatException. Parsing dates and times in .NET.

How to convert this date 2017-07-09T17:50:21.000-0500 | C#

when i run the below code,
string dt = "2017-07-09T17:50:21.000-0500";
DateTime date = Convert.ToDateTime(dt);
it gives me output as
7/10/2017 4:20:21 AM
where as i want my output to be
2017-07-09 17:50
update
the code #alexander-petrov gave worked
string dt = "2017-07-09T17:50:21.000-0500";
string date = DateTimeOffset.Parse(dt).DateTime.ToString("yyyy-MM-dd HH:mm");
gives output
2017-07-09 17:50
but on inserting the same to database it is adding +5 hrs to the time and inserting as
2017-07-09 22:50
This is a Round-Trip format of a DateTime specified with a DateTimeKind.Local kind.
You need to decide if your program needs to be aware of time zones or not.
You could try parsing it while supplying the System.Globalization.DateTimeStyles.RoundtripKind or System.Globalization.DateTimeStyles.AdjustToUniversal parameter to the Parse method.
If you want take offset into account then use DateTimeOffset type.
string dt = "2017-07-09T17:50:21.000-0500";
DateTimeOffset date = DateTimeOffset.Parse(dt);
// format on my machine
// 09.07.2017 17:50:21 - 05:00
Console.WriteLine(date);
// without offset
// 09.07.2017 17:50:21
Console.WriteLine(date.DateTime);
I couldn't get your date to work, as I think there is a colon missing in the last part. Adding that colon back allows me to convert the XSD date time into a SQL DATETIME using this script:
DECLARE #stringDate VARCHAR(30);
SELECT #stringDate = '2017-07-09T17:50:21.000-05:00';
DECLARE #xmlDate XML;
SELECT #xmlDate = CAST('' AS XML);
SELECT #xmlDate.value('xs:dateTime(sql:variable("#stringDate"))', 'datetime');
Results:
2017-07-09 22:50:21.000
Try:
string date = "2017-07-09T17:50:21.000-0500";
DateTime d = DateTime.ParseExact(date, "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzzz", null);

convert back datetime format toLongdatestring to (M/DD/YYYY h/mm/ss)

hi i have datetime format in database like this
1/18/2014 4:14:52 PM (M/DD/YYYY h/mm/ss)
i convert it to ToLongDateString
string date = Convert.ToDateTime(myQuizOccurrence.occurred).ToLongDateString();
**result ->** **Sunday, January 12, 2014**
i want to convert back again that result date to become same format as database i wonder how to do it?
edited
so far i already try as #matt says using datetime instead string
DateTime dt2 = (DateTime) myDataGridView.CurrentRow.Cells[3].Value;
i already check it's have same format as datetime in database
but when i try to matching in query with this following code
Global.dbCon.Open();
string kalimatsql2 = "SELECT * FROM Quiz_Occurrences WHERE Occurred = " +dt2+ "
ORDER BY ID";
Global.reader = Global.riyeder(kalimatsql2);
if (Global.reader.HasRows) {
while (Global.reader.Read()) {
int idku = Convert.ToInt32(Global.reader.GetValue(0));
MessageBox.Show(idku.ToString());
}
}
Global.dbCon.Close();<br>
it's give error result
Syntax error (missing operator) in query expression 'Occurred = 1/12/2014 4:18:59 PM'
what i'm missing?
The vast majority of databases you will interact with should be accepting either a DateTime or a DateTimeOffset type directly. You would not use a string when retrieving data from the database, nor when sending data back to it. Therefore, format is irrelevant.
My guess is you are doing something similar to this:
DateTime dt = Convert.ToDateTime(mydatareader["MyDateTime"].ToString());
Instead you should be doing this:
DateTime dt = (DateTime) mydatareader["MyDateTime"];
When you save it back to the database, you should be using parameratized inputs that will take the DateTime directly. If you're trying to concatenate a string to build an SQL statement, you're doing it wrong.
i have datetime format in database like this
The best practice is to store date and time information with DateTime or DateTimeOffset type.
To convert back your string to DataTime you can use this:
string str = "Sunday, January 12, 2014";
var dateTime = DateTime.ParseExact(str, "D", CultureInfo.CurrentCulture);
Note that you loss the time part when you convert it to long date.

Categories

Resources