Convert to datetime from Oracle - c#

i know there are a lot of similar questions, but I couldn't find what I was looking for.
Here is my oracle date:
string testdate= "2014-01-07 15:00:00.0000000";
And here is how I tried to convert to datetime:
DateTime.ParseExact(testdate, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture)
This throws a format exception. Any ideas?
My quick test also throws the string not valid datetime exception. Quick test:
Console.WriteLine(DateTime.ParseExact(testdate, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture).ToShortDateString());

I'd start by trying to avoid getting it as a string in the first place. Make sure you're using the appropriate data type in Oracle, and you should be able to call GetDateTime on the appropriate DataReader (or whatever you're using).
If you must parse it as text, then you need to specify a format which matches the value - so use 7 fs instead of 3, given that your value has ".0000000" at the end.
DateTime.ParseExact(testdate, "yyyy-MM-dd HH:mm:ss.fffffff",
CultureInfo.InvariantCulture)
But again, I'd strongly urge you to avoid having to deal with the value as text at all.

Why use ParseExact at all? Reqular Parse seems to work.
var dt = DateTime.Parse("2014-01-07 15:00:00.0000000", CultureInfo.InvariantCulture);
// Prints out 2014-01-07T15:00:00.0000000
Console.WriteLine(dt.ToString("o"));

Related

encountering String was not recognized as valid datetime using ParseExact

I want to insert the DateTime.Now as dd-MMM-yyyy format, but it is giving me string is not recognized as valid datetime while I use ParseExact.
db.AddInParameter(objdbCommand, "#dtAddedOn", DbType.DateTime, DateTime.ParseExact(Convert.ToString(DateTime.Now), #"dd-MMM-yyyy", System.Globalization.CultureInfo.InvariantCulture));
I have also tried :
DateTime.ParseExact(Convert.ToString(DateTime.Now), #"dd-MMM-yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture));
but it is giving me the same error
Since you are inserting a DateTime anyway, you do not need to Convert to string and parse back to DateTime.
db.AddInParameter(objdbCommand, "#dtAddedOn", DbType.DateTime, DateTime.Now);
will do the trick.
DateTime does not have a format. Format comes into play as soon as you need a textual representation of the value that the DateTime represents. I also wouldn't recommend to use Convert for this but one of DateTime.ToString overloads.
Edit:
If you do not want to include the Time part, i.e. insert the Date, only you can use DateTime.Now.Date (see Date Property) or even easier DateTime.Today. This will give you a DateTime object with Time components all set to zero.
Edit 2:
Mind that there are some inherent problems using DateTime, especially if your system is going to be used spanning different TimeZones. Going deeper into this would go beyond the scope of this answer, though. Just want to give you a heads-up.
You may want to checkout DateTimeOffset and related Articles like Choosing between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo

C#, datetime.parse Error 32510 can not parse

everyone.
I have a datetime coming back from a music file in the format:
32510
Maybe, it means 1989/01/02
How can i get the datetime.parse function to pick up on this? Ie parse it without erroring? Cheers
This DateTime(32510) is in double so we can't simply use datetime.parse to convert 32510 to DateTime. To convert a double to date we need to use DateTime.FromOADate method.
For more details you can go through this MSDN link:
https://msdn.microsoft.com/en-us/library/system.datetime.fromoadate(v=vs.110).aspx
Quite often interop dates are stored as integers, so you'll need to convert them to actual dates. See below as an example:
var dt = DateTime.FromOADate(32510);
Console.WriteLine(dt);
Where the output is:
2/01/1989 12:00:00 AM
I don't think you can use DateTime.Parse() to convert 32510 to 1989/01/02 though.
It sounds me like Ole Date, try using DateTime.FromOADate
DateTime date = DateTime.FromOADate(32510)
//output - 1/2/1989 12:00:00 AM

SQL datetime to C# string and back to SQL datetime

I have a webservice method that gets data from sql of the format
2012-11-18 11:21:03 when i save it to C# string it becomes this format: 18.11.2012 11:21:03
How do i change it back to the SQL format 2012-11-18 11:21:03 ?
Parse it into a dateTime again
DateTime myTime = DateTime.Parse(myString);
and back into a proper to string
myTime.ToString("yyyy-MM-dd HH:mm:ss");
Or just read it into a datetime and cut out the middleman.
You can get the universally sortable string format (which looks like the one used by SQL server) by using the format string "u" like this:
var dateTimeString = String.Format("{0:u}", yourDateTime);
Simply run the below code,
var newDateTime = oldDateTime.Date.ToString("yyyy-MM-dd HH:mm:ss");
Its just converting it back to the SQL Format DATETIME
Trouble with Dates as strings is they are ambiguous and the formats can vary based on where you are in the world, or even local machine settings. You might assume a date string is yyyy-mm-dd but what if it is actually yyyy-dd-mm? Some dates will appear to work and some will be invalid.
In other words is 2013-02-10 the 10th of February or is it the 2nd of October? If it is just a string you have no way of knowing for sure what was intended.
Your best bet as suggested by #Haedrian is to store in a DateTime C# object, not a string. That way it is never ambiguous and you have access to various date specific functions. If you must store as a string you can convert back to a date as above or use
DateTime.TryParse(datestring, out dateVariable);
which won't throw an exception for an invalid format. Depends if you want exceptions!
Also I would suggest if you must use strings to use a 3 character month in strings, which again eliminates the ambiguity, e.g.
"dd-MMM-yy hh:mm tt"

Exception on DateTime Conversion

I'm trying to format a list of datetime. One date is in the format same as what i provided but the factors are not in place. That line of code is given below. Can someone tell me how to skip the error for the below line?
Convert.ToDateTime("22-01-2013 00:00:00").ToString("yyyy-MM-dd");
I would avoid using Convert.ToDateTime to start with. I would suggest using DateTime.TryParse or (preferrably) DateTime.TryParseExact. Both of these will return a value indicating whether the conversion succeeded, so you don't need to start catching exceptions in order to skip bad data. For example:
DateTime parsed;
if (DateTime.TryParse(text, out parsed))
{
string reformatted = parsed.ToString("yyyy-MM-dd");
// Use reformatted
}
else
{
// Log error, perhaps?
}
If you have multiple possible formats, you should consider using the overload of TryParseExact which allows you to specify multiple formats in a single call.
As well as the format, you should consider the culture you want to use. In the above code (and your code) it will use the executing thread's culture. Is that always what you want? The culture can affect all kinds of things - usually if you're specifying a custom format, you want to use the invariant culture. Otherwise you could end up using a non-Gregorian calendar unexpectedly, for example...
EDIT: If your input is always in the format dd-MM-yyyy, then you should probably use:
DateTime parsed;
if (DateTime.TryParseExact(text, "dd-MM-yyyy", CultureInfo.InvariantCulture,
DateTimeStyles.Default, out parsed))
{
string reformatted = parsed.ToString(CultureInfo.InvariantCulture,
"yyyy-MM-dd");
// Use reformatted
}
else
{
// Log error, perhaps?
}
Instead of Convert.ToDateTime use DateTime.Parse or DateTime.ParseExact
ParseExact gives you more control over the format, so for example:
DateTime.ParseExact("22-01-2013 00:00:00","dd-MM-yyyy HH:mm:ss",CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
There is also a TryParseExact variant, which allows you to gracefully handle parse errors.
Try with:
DateTime.ParseExact("22-01-2013 00:00:00","dd-MM-yyyy HH:mm:ss",CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");
This way you can specify the exact format for your date-string.
Try to use DateTime.ParseExact() method instead of.
Converts the specified string representation of a date and time to its
DateTime equivalent.
public static void Main(string[] args)
{
Console.WriteLine(DateTime.ParseExact("22-01-2013 00:00:00", "dd-MM-yyyy HH:mm:ss", CultureInfo.CurrentCulture).ToString("yyyy-MM-dd"));
}
Here is a DEMO.
Also check out Coding Best Practices Using DateTime in the .NET Framework which I think every .NET developer should read.

Converting String Format "yyyy-MM-ddTHH:mm:ss.fffZ" to DateTime

I know this question has been asked a number of different ways, and I have looked at them all and none of the solutions seem to work for me. So, I am hoping that maybe you guys can give me a quick hand.
The input string is: "2000-01-01T12:00:000Z". I need to take that input string and convert it to DateTime so that it can be stored in the database.
I have been using ParseExact, but I keep getting the not recognized date string exception. Where am I going wrong?
inValue.LatestDepartTime = "2000-01-01T12:00:000Z";
DateTime _latestDepartTime = DateTime.ParseExact(inValue.LatestDepartTime, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
Your format string needs to exactly match the input.
That includes the literal T and Z characters.
Use yyyy-MM-dd'T'HH:mm:ss.fff'Z'
The code is:
public DateTime convertIsoToDateTime (string iso)
{
return DateTime.ParseExact(iso, "yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture);
}
You need to include \\T and \\Z in your format string to match the literals T and Z.
You need to put single quotes around the T and Z:
DateTime parsedDateTime;
DateTime.TryParseExact(obj, "yyyy-MM-dd'T'HH:mm:ss'Z'", null, System.Globalization.DateTimeStyles.None, out parsedDateTime);
return parsedDateTime;
You don't specify the T in the pattern.
That said, you may want to have a look at the XmlConvert class, which provides the methods for converting this format.

Categories