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

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

Related

How to input a formatted date in a text box?

I'm confuse about how to make an input of formatted date time and currency. I want user to input the DoB as dd/mm/yyyy but when I'm using DateTime data type in Visual Studio it only get yyyy/mm/dd format.
Here's my code:
This is DoB and property from another class employee.cs
class employee
{
private DateTime myBOD;
public DateTime BOD
{
get
{
return myBOD;
}
set
{
myBOD = value;
}
}
}
This is the main form1.cs
vemployee.BOD = Convert.ToDateTime(bod.Text);
var today = DateTime.Today;
age.Text = Convert.ToString(today.Year-vemployee.BOD.Year);
Well, DateTime is a struct it doesn't have any format but properties like Year, Month, Day etc.
use DateTime.ParseExact when you want to obtain DateTime from string:
vemployee.BOD = DateTime.ParseExact(
bod.Text,
"dd'/'MM'/'yyyy", // Please, note that "mm" stands for minutes, not months
CultureInfo.InvariantCulture);
And .ToString(format) when you want to represent DateTime as a string
DateTime today = DateTime.Today;
bod.Text = today.ToString("dd'/'MM'/'yyyy", CultureInfo.InvariantCulture);

Getting date in correct formatted for with proper timezone, among list of strings in an a array

I have a set of array.
//this is not hard corded, some times array will have multiple no.of strings in date format.
["vishnu","2016-08-31T18:30:00.000Z","1992","banglore"]
I have an array of strings, among these strings there is one string which is in date format.
I need to do a foreach and need to check which string is in the date format.
If we got the date string "2016-08-30T18:30:00.000Z" I need to convert it to basic date format but in correct timezone, here the date is 2016-08-31 but what I need as out put is
["vishnu","31/8/2016","1992","banglore"]
not
//check the difference in date!
["vishnu","30/8/2016","1992","banglore"]
the aim is from the array, if string is in date string format, convert it.
public static void Main(string[] args)
{
string inputString = "2016-08-31T18:30:00.000Z";
DateTime enteredDate = DateTime.Parse(inputString);
Console.WriteLine(enteredDate);
DateTime dDate;
if (DateTime.TryParse(inputString, out dDate))
{
DateTime dtx = enteredDate.ToLocalTime();
String.Format("{0:d/MM/yyyy}", dDate);
Console.WriteLine(dtx);
}
else
{
Console.WriteLine("Invalid"); // <-- Control flow goes here
}
// DateTime dt = convertedDate.ToLocalTime();
}
If you need to correct the DateTime for the time zone, you can use TimezoneInfo.ConvertTime():
string inputString = "2016-08-31T18:30:00.000Z";
DateTime dDate;
if (DateTime.TryParse(inputString, out dDate))
{
DateTime correctedDateTime = TimeZoneInfo.ConvertTime(dDate, TimeZoneInfo.Local);
// write this here back into the array using your format
Console.WriteLine(correctedDateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));
}
else
{
Console.WriteLine("Invalid"); // <-- Control flow goes here
}
For further reference check out this post. This answer is inspired by it to use TimeZoneInfo.
DateTime dDate;
do this operation iside foreach
if (DateTime.TryParse(answerString, out dDate))
{
DateTime enteredDate = DateTime.Parse(answerString);
var Date = enteredDate.ToString("dd/MM/yyyy");
answerString = Date;
Console.WriteLine(answerString);
}
else{
//operation
}
thanks to mong zhu
Try using DateTimeOffset rather than DateTime as it is built to handle time zones.
Here's the code:
string inputString = "2016-08-31T18:30:00.000Z";
DateTimeOffset enteredDate = DateTimeOffset.Parse(inputString);
Console.WriteLine(enteredDate);
DateTimeOffset dtx = enteredDate.ToLocalTime();
Console.WriteLine(dtx);
This produces the following for me in GMT+09:30:
2016/08/31 18:30:00 +00:00
2016/09/01 04:00:00 +09:30
To get it in Indian time try this:
DateTimeOffset dtx = enteredDate.ToOffset(TimeSpan.FromHours(5.5));
Console.WriteLine(dtx);
I get 2016/09/01 00:00:00 +05:30 now.

Failing when casting to DateTime object

I have this CSV
"06/04/2016 17:24:14,1443.92,0.31"
Which I try to convert into the following object
public class FooModel
{
public DateTime Date { get; set; }
public DateTime Time { get; set; }
public string Index { get; set; }
public string Change { get; set; }
}
with the following code
string[] values = line.Split(',');
FooModel m = new FooModel
{
Date = DateTime.ParseExact(values[0], "dd/MM/yyyy", CultureInfo.InvariantCulture),
Time = DateTime.ParseExact(values[0], "H:mm:ss", CultureInfo.InvariantCulture),
CultureInfo.InvariantCulture),
Index = values[1],
Change = values[2],
};
and failing on the exception
"String was not recognized as a valid DateTime."
How can I cast to DateTime Object
EDIT
I saw couple of answers that almost worked however it was my bad to mention that the date is formatted as Day-Month-Year. this means that it is failing when the csv is set to "22/12/2014 16:24:04,1476.83,-0.74"
I would guess the issue you're having is with the ParseExact part of this.
Why are you converting both the date and the time separately? It seems easier to do this:
DateTime Date = DateTime.Parse(values[0]);
string time = Date.ToLongTimeString();
string date = Date.ToLongDateString();
This way it's saved in the same variable and you can use the pieces as you need.
From the documentation:
The format of the string representation must match the specified format exactly.
The input string is:
"06/04/2016 17:24:14,1443.92,0.31"
The format string is:
"dd/MM/yyyy"
Those aren't really exact. Just use Parse instead:
Date = DateTime.Parse(values[0]);
This gives you the complete DateTime value, so you don't even need the Time property on the model. No need to store the same information twice, after all.
Additionally, you might use TryParse to be a little safer with the input:
DateTime temp;
if (!DateTime.TryParse(values[0], out temp))
{
// parsing error. notify the user?
}
Date = temp;
string[] s = "06/04/2016 17:24:14,1443.92,0.31".Split(',');
DateTime date = DateTime.Parse(s[0]);
This worked for me.
When you split the string values[0] = 06/04/2016 17:24:14 and you are parsing the Date and the Time component separately. Instead you need to parse them together with
DateTime date = DateTime.ParseExact(values[0], "dd/MM/yyyy H:mm:ss",
CultureInfo.InvariantCulture);
and access the date by
date.Date
and access the time by
date.Time

how to input DateTime into MySQL via C#

I'm having a huge issue with inputting DateTime into my MySQL db. MySQL reads datetime as yyyy-MM-dd HH:mm:ss while C# sees datetime as dd/MM/yyyy HH:mm:ss. I have tried two different examples and both doesn't work.
MODEL
public class DateAndTime
{
public DateTime DateTime { get; set; }
}
CONTROLLER
//I Have two examples that doesn't work.
var myDateTime = "2016-04-08 12:00:00" //this gives the error "cannot covert source 'string' to tartget type System.DateTime
var myDateTime = Convert.ToDateTime("2016-04-08 12:00:00") //this gives the error "Input string was not in a correct format."
var model = new DateAndTime
{
DateTime = myDateTime
};
So I'm stuck. I'ms sure someone out there has had this issue.
DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
System.Globalization.CultureInfo.InvariantCulture);
Check:
Converting a String to DateTime
https://msdn.microsoft.com/en-ca/library/cc165448.aspx
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
I have this issue because of the datetime format in my machine. If your desktop is configured like dd/mm/yy(the / symbol instead of -) then you have to replace - with / before converting. Please let me know
try this :
myDateTime.ToString("yyyy-MM-dd HH:mm:ss");
myDateTime variable must be type DateTime.
or you can use this MySql function : STR_TO_DATE
STR_TO_DATE('4/8/2016 2:18:17 PM', '%m/%d/%Y %h:%i:%s %p')
Specifier Format here

String date time format

I am using the Vimeo API and I want to convert the string <upload_date> to a short date format, {0:d} or {0:dd/mm/yyyy}.
This is my code but it doesn't seem to be working for me.
select new VimeoVideo
{
Date = String.Format("{0:d}",(item.Element("upload_date").Value)),
};
return Vids.ToList();
}
public class VimeoVideo
{
public string Date { get; set; }
}
As Oleg suggested you can try to parse your value to DateTime and then format it (use try catch if needed). That should work (not 100% sure since I don't know what item's type is).
var myDate = DateTime.Parse(item.Element("upload_date").Value);
Date = String.Format("{0:d}", myDate);
http://msdn.microsoft.com/it-it/library/1k1skd40(v=VS.80).aspx
Just verify the type of the Value property.. The above string formatter works for System.DateTime structure.. I assume in your case its string type object. According to the given sample date time string i have written this code.. Try out this.
CultureInfo provider = CultureInfo.InvariantCulture;
var format = "yyyy-MM-dd HH:mm:ss";
var dt = DateTime.ParseExact(item.Element("upload_date").Value, format, provider);
Date = string.Format("{0:d}", dt);
Hope it works..

Categories

Resources