Parsing Oracle Date to C# datetime - c#

I need to Parse the following string as a DateTime in c#:
"22-FEB-21 09.52.41.256898000 AM"
I've tried the following but it throws exception:
DateTime.ParseExact(
"22-FEB-21 09.52.41.256898000 AM",
"DD-MON-YY HH.mm.ss.ff AM",
CultureInfo.InvariantCulture);
The exception being thrown is
String was not recognized as a valid DateTime.

Try
d-MMM-yy h.m.s.ffffff'000' tt
format string. I.e.
var result = DateTime.ParseExact(
"22-FEB-21 09.52.41.256898000 AM",
"d-MMM-yy h.m.s.ffffff'000' tt",
CultureInfo.InvariantCulture);
Format explained:
d - day in one ore two digit format
MMM - month (abbreviation)
yy - year (two digits)
h - hour 1..12 or 01..12
m - minutes 00..59 or 0..59
s - seconds 00..59 or 0..59
ffffff - fraction of seconds
'000' - 000
tt - AM or PM

There are a couple of problems with your date string.
First, are you sure you are getting 9 decimal places? Since Oracle only supports 6 decimals of precision, maybe you can do something on the query side to remove those?
Also your format string has some problems.
It should be MMM not MON for the month
It should be hh since you are using a 12 hour clock standard (AM/PM) and not 24 hours.
Then you need to fix your fractional seconds, and use a string match for the last two zeros.
Your format string ends up to be:
"d-MMM-yy hh.mm.ss.fffffff'00' tt"
So to test it, you can run this:
var date = DateTime.ParseExact(
"22-FEB-21 09.52.41.258998000 AM",
"d-MMM-yy hh.mm.ss.fffffff'00' tt", CultureInfo.InvariantCulture);
Console.WriteLine(date);
That should solve your problem.

Related

How to parse custom string to DateTime C#?

I need to parse to following Date Aug 20 11:38:43 2017 GMT
I'm trying to use DateTime.TryParseExact but can't find the correct format.
my latest format is MMM dd hh:mm:ss yyyy
my code :
string nextUpdate; //Next Update: Aug 20 11:38:43 2017 GMT
string dateTimeFormat = "MMM dd hh:mm:ss yyyy";
DateTime crldt;
DateTime.TryParseExact(nextUpdate.Split(':')[1].Trim(), dateTimeFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out crldt);
when I run the code I get crldt ~ Date = {1/1/01 12:00:00 AM}
my question : what format should I use or what alternative way can I use to parse this string to DateTime
UPDATE
using suggestions from : #Sergey Berezovskiy
I've updated the code to :
string nextUpdate; // Next Update: Oct 7 06:16:18 2017 GMT
string dateTimeFormat = #"MMM dd HH:mm:ss yyyy \G\M\T";
Regex r =new Regex(".*Next Update:.*");
nextUpdate = r.Match(Crltext).Value;
DateTime crldt;
DateTime.TryParseExact(nextUpdate.Substring(nextUpdate.IndexOf(':')+1).Trim(),
dateTimeFormat, System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AssumeUniversal, out crldt);
int intDTComp = DateTime.Compare(crldt, DT_now);
I've found a date that doesn't fit this format : Next Update: Oct 7 06:16:18 2017 GMT
what is the issue now ?
UPDATE 2
I've found the issue , but can't find a clean solution.
The issue is that the problematic date is Oct 7 ... ,
while the format is MMM dd ...
my workaround is adding another format MMM d hh:mm:ss yyyy and using it if date = {1/1/01 12:00:00 AM}
what other solution may I use in this scenario
First of all, don't forget that your string contains "GMT". You should either remove it from the string, or add to format pattern:
string nextUpdate = "Next Update: Aug 20 11:38:43 2017 GMT";
string format = #"MMM dd hh:mm:ss yyyy \G\M\T";
Next - don't split input string by : because there is another : symbols in the string. And you will get array with parts ["Next Update", " Aug 20 11", "38", "43 2017 GMT"]. Taking the second item from array gives you " Aug 20 11". Instead, you should just take substring after first : occurance:
string s = nextUpdate.Substring(nextUpdate.IndexOf(':') + 1).Trim();
And finally parse that string using your format:
IFormatProvider provider = CultureInfo.InvariantCulture;
DateTime date = DateTime.ParseExact(s, format, provider, DateTimeStyles.AssumeUniversal);
Output will depend on your time zone. E.g. for my time zone GMT+3 it will be:
8/20/2017 14:38:43
If this is your string:
"Next Update: Aug 20 11:38:43 2017 GMT"
Then when you do this:
nextUpdate.Split(':')[1].Trim()
You get this:
"Aug 20 11"
Which doesn't match your date format. I suspect you don't just want the second split value, but also all remaining split values. You can re-join them. Something like this:
string.Join(":", nextUpdate.Split(':').Skip(1)).Trim()
This would split them by the ":" character, skip the first one but keep all remaining ones, and re-join the remaining ones into another string with the ":" character again.
Note: You may also need to account for that time zone value. There are some helpful ideas on this question for how to do that.
If that's the input, I propose that you take the format exactly as the input
string nextUpdate = "Next Update: Aug 20 11:38:43 2017 GMT";
string dateTimeFormat = #"\N\e\x\t\ \U\p\d\a\t\e\:\ MMM dd hh:mm:ss yyyy\ \G\M\T";
DateTime crldt;
crldt = DateTime.ParseExact(nextUpdate, dateTimeFormat , System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);
This way, when reading the code it's very clear what the expected format is, and you don't have code with Split() or other items that need explanation.
Also note that if you leave the colons (:) like that, they may be replaced by .NET to match the hour separator. Use \: if you always require a literal colon.
As I wrote in the comments before, note that you're ignoring the time zone.
Use following code
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime givenDate = DateTime.ParseExact("Aug 20 14:38:43 2017 GMT", "MMM dd HH:mm:ss yyyy GMT", provider); // here HH is for 24 hour format . use hh for 12 hour format
string expectedDate = givenDate.ToString("dd/MM/yy hh:mm:ss tt"); // tt is for AM or PM (no need to use tt if you use hour as HH I mean 24 hour format)
Your Output will be 20/08/17 11:38:43 AM

Convert String to DateTime(yyyy-mm-dd)

I'm parsing date from server, date is in this format 6/16/2016 3:15:29 PM Could you help me please convert date to 2016-06-16?
I tried:
DateTime date = DateTime.ParseExact(datestring, "MM/dd/yyyy h-m-s t", System.Globalization.CultureInfo.InvariantCulture);
string formattedDate = date.ToString("yyyy-MM-dd")
but it's giving me error.
You've got 3 problems
You're not using the correct time separators
You're using only one t when you need two
You're using two M when you only need one
Try
DateTime date = DateTime.ParseExact(datestring, "M/d/yyyy h:m:s tt", System.Globalization.CultureInfo.InvariantCulture);
string formattedDate = date.ToString("yyyy-MM-dd");
The reason you need only one M is because MM expects a leading zero. Since the values of the date and time are delimited it's better to use the single versions for month, day, minutes, and seconds because they will work for values with or without leading zeros.
To execute DateTime.ParseExact() format of the input string and the format string must be the same. try this:
DateTime date = DateTime.ParseExact(datestring, "M/dd/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);
string formattedDate = date.ToString("yyyy-MM-dd");
These are interesting in the given input string(6/16/2016 3:15:29 PM):
The month is represented in single digit so it should be M instead for MM. We use MM if it is specified as 06.
Same in the case of Hours too. It should be h instead for normal hh
There is a single space in between Date and Time as well as Time and PM.
So we must consider all of these while generating the Format-string for ParseExact

Datetime.parseExact gives (1-9) day's value with single digit, without 0

I have this code, it gives day's value as 1,2,3 .. instead of 01,02,03..
(DateTime.ParseExact("20160416", "yyyyMMdd", CultureInfo.InvariantCulture))
gives: 4/16/2016 12:00:00 AM.
I need 04/16/2016 12:00:00 AM
I have tried different cultures but nothing worked.
DateTime doesn't store any formatting information, it's just a structure representing a date and time. ParseExact is parsing your date string correctly.
If you want it formatted, you supply a format to DateTime.ToString, for example:
var formattedDate = dateTime.ToString("MM/dd/yyyy hh:mm:ss tt");
See this fiddle.
DateTime.ParseExact returns DateTime which doesn't have any implicit format. This "format" concept only applies when you get it's textual (a.k.a. string) representation.
You didn't told use how and where you see this 4/16/2016 12:00:00 AM string but if you wanna get days part with leading zero, you can use The dd format specifier with a proper culture (for calendar and time designators).
The dd custom format string represents the day of the month as a
number from 01 through 31. A single-digit day is formatted with a
leading zero.
DateTime dt = DateTime.ParseExact("20160416", "yyyyMMdd", CultureInfo.InvariantCulture);
string str = dt.ToString("MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
// 04/16/2016 12:00:00 AM

convert string to datetime format invalid System.Datetime

I have been trying many different solutions found here but none works. I want to convert the string to the format of dd/MM/yyyy
editField["ExpiryTime"] = "5/19/2011 12:00:00 AM";
DateTime dt = DateTime.ParseExact(editField["ExpiryTime"].ToString(), "dd/MM/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture);
But I always get an error of invalid System.DateTime. Pleaes help!
Use CultureInfo.InvariantCulture to avoid culture issues like invalid date separators and this format:
M/dd/yyyy hh:mm:ss tt
Uppercase M is for months, dd are the days, yyyy the four digit years. Lowercase hh are the hours in 12h format(required in combination with AM/PM), mm are the minutes, ss the seconds and tt the AM/PM designator.
string input = editField["ExpiryTime"].ToString(); // "5/19/2011 12:00:00 AM"
DateTime dt = DateTime.ParseExact(input, "M/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
I want to convert the string to the format of dd/MM/yyyy
Then use ToString in the same way, CultureInfo.InvariantCulture forces / as date separator, without it will be replaced with your current culture's date-separator:
string result = dt.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
If you need it as string, then you should try this
var dt = string.Format("{0:dd/MM/yyyy}",DateTime.Now);
Note: Also check your local system date time format. If it mismatches with the used one , still you might experience the same exception..

How can I get this DateTime format in .NET

I'm trying to format some DateTime into this W3C DateTime format :-
Complete date plus hours and minutes:
eg. YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
where:
YYYY = four-digit year
MM = two-digit month (01=January, etc.)
DD = two-digit day of month (01 through 31)
hh = two digits of hour (00 through 23) (am/pm NOT allowed)
mm = two digits of minute (00 through 59)
ss = two digits of second (00 through 59)
s = one or more digits representing a decimal fraction of a second
TZD = time zone designator (Z or +hh:mm or -hh:mm)
I originally had this...
var myDateTime = someDateTime.ToString("s",
System.Globalization.CultureInfo.InvariantCulture);
But that results in a string of :
2011-08-31T08:46:00
Can anyone help?
You want "o":
var myDateTime = someDateTime.ToString("o",
System.Globalization.CultureInfo.InvariantCulture);
Use the following:
yourDateTime.ToString( "yyyy-MM-ddTHH:mmK", CultureInfo.InvariantCulture );
Here is more than you'll ever want to know on DateTime formats:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
I believe you want
"yyyy-MM-ddTHH:mmK"
Note:
HH rather than hh to be 24 hour
K to specify the time zone; this relies on the DateTime.Kind being UTC or local; unspecified will end up with an empty string
You should also use CultureInfo.InvariantCulture to make sure no funky culture information is used. (You could quote the - and : as an alternative, but I'd use the invariant culture to make sure.)
You can format it like this:
someDateTime.ToString("yyyy-MM-dd");
Here's the documentation of the 'standard' supported datetime format strings:
http://msdn.microsoft.com/en-us/library/az4se3k1(v=VS.100).aspx
someDateTime.ToUniversalTime().ToString("u");
Will get you pretty close => '2011-09-02 10:22:48Z'. If that isn't good enough, then you can create a custom format string that includes the "T" (see 'Custom Date and Time Format Strings').

Categories