Convert 12:00:00.000 always to 12AM issue - c#

I had an issue like this. In my development environment, when I read the record from SQL Database: 12:00:00.000, the convertion always return 12PM in my application. But in the customer environment, it always return 12AM....and of course it's wrong
Have you ever faced this issue?
Thank & best regards,

Assuming "12:00:00.000" is a string, consider converting it to a DateTime using the following method call:
string myValue = "12:00:00.000";
DateTime myDate = DateTime.ParseExact(myValue, "HH:mm:ss:fff");
Using HH as the hour, a 24h date format is used.
Remember: this only works in the exact format specified in the input.

return DateTime.ParseExact("12:00:00.000", "HH:mm:ss:fff");

Related

C# Converting to date from inconsistent string

I'm trying to parse a file where I get my dates as string like those:
5/18/2020 8:38:32 AM
6/8/2021 10:11:42 PM
11/24/2021 9:21:54 AM
----
I tried to use a DateTime.TryParse on my string and test the "---" case in a if statement which work but it succeed to convert only the 6/8/2021 12:41:56 PM.
I tried to use TryParseExact and specify a date format but it seem that I should make a case months with one and two digits and same the days.
I guess there is something I'm not seeing or don't know.
Thanks for you help.
It is because you are probably on a culture other than en-US which those dates are formatted in. Use IFormatProvider parameter. ie:
void Main()
{
var dates = #"5/18/2020 8:38:32 AM
6/8/2021 10:11:42 PM
11/24/2021 9:21:54 AM
----";
foreach (string s in dates.Split('\n'))
{
if (DateTime.TryParse(s, new CultureInfo("en-US"), DateTimeStyles.None, out DateTime d))
{
Console.WriteLine(d);
}
}
}
Here is the .Net fiddle link.
EDIT: Note that the version on .Net fiddle is slightly different because of the older C# version there.
Without the exact details, I have to guess:
If he only can translate the 6/8 date, you may have the wrong locale settings (you have something like MM/dd/yyyy .... but this works only for the 8th of june, what you might get wrong with 6th of august)
If you use ParseExact, you can also provide a list of valid format strings.
EDIT
Cetins answer is correct. Additionally, the title of the post is a bit confusing, because the datetime string IS consistent (in the 'en-US' local settings)
#Cetin Basoz You are right, it was indeed a culture problem. Thank you!
#nabuchodonossor You are right about the datetime string ("----" apart) being consistent. What I wanted to say was that there is no every time two digits for the days or months which would not happen if the dates were something like 05/18/2020 and 06/08/2021. Sorry, I have a hard time being precise.

Datetime to string: differents behavior depending on the converted datetime

I use this C# code to convert a datetime to a string:
MyDatetime.ToString("dd/MM/yyyy HH:mm")
it works, but not every time. What do I mean?
If the input datetime is, for example, 2016-10-19 17:27:41.727, I get the string as expected, 19/10/2016 17:27. If the day in datetime (and/or the month) has only one digit, I get something weird.
If the input is 2016-01-07 14:58:13.560, I get 1/7/2016 and if it is 2016-10-26 17:14:16.000 I get 10/6/2016.
Do you know why? How can I always set a leading zero for days and months with only one digit? And, further, why I don't see the time part in the date I wrote as examples?
UPDATE
.
Some datetime fields from a SQL Server database (this is SQL Server Management Studio).
Most probably your DateTime already has invalid value (day and month are mixed)
new DateTime(2016, 01, 07,14,58,13,56).ToString("dd/MM/yyyy HH:mm")
returns 07-01-2016 14:58.
Take a look how do you read this DateTime value from the database. I believe the problem is there. (for example SqlDataReader.GetDateTime)
When you input a date as "XXXX-XX-XX" it assumes you're using the format "YYYY-MM-DD".
Just look at your input-output and you can see the pattern.
A lot of people in programming (that I work with) use this format because it is auto-filtering without any punctuation (20170102 will always go after 20161231, etc).
The DateTime method works in conjunction with the computer language. If your computer (or server) is in English (or vice versa) and you pass an American non-standard date format, you will have problems like this.
If you are using a web application, configure the correct language in web.config

The string was not recognized as a valid DateTime. There is an unknown word starting at index 0

I have the following C# that is giving me the error above when trying to parse string to datetime.
DateTime backupdate = System.Convert.ToDateTime(imageflowlabel.Text);
DateTime currentdate = System.DateTime.Now.AddHours(-2);
int result = currentdate.CompareTo(backupdate);
imageflowlable.text looks like this 2012-04-15 15:23:34:123
Any ideas on how to convert this?
Thanks
Yes - use "DateTime.ParseExact()" or "TryParseExact()" with a custom format string:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
DateTime currentdate;
int result;
try
{
// EXAMPLE: 2012-04-15 15:23:34:123
DateTime backupdate =
DateTime.ParseExact (
"yyyy-MM-dd HH:mm:ss:fff", //mind the casing
imageflowlabel.Text,
CultureInfo.InvariantCulture);
currentdate = System.DateTime.Now.AddHours(-2);
result = currentdate.CompareTo(backupdate);
}
catch (Exception ex)
{
...
Your problem is with the time part of your dateTime string. If your string read "2012-04-15 15:23:34.123" then it would work. You could modify your string and replace the last colon with a period and that would fix it.
Your code looks correct; the issue is presumably with your string format, whose last : should actually be a . (indicating the start of the fractional seconds).
Incorrect: 2012-04-15 15:23:34:123
Correct: 2012-04-15 15:23:34.123
Convert.ToDateTime("2012-04-15 15:23:34.123") works fine.
ParseExact should work for you, assuming your users have no way of editing that value on their own; in that case, you should use TryParseExact to unless you want the FormatException.
var toParse = "2012-04-15 15:23:34:123";
var parsed = DateTime.ParseExact(toParse, "yyyy-MM-dd HH:mm:ss:fff", null);
Assert.AreEqual(new DateTime(2012, 4, 15, 15, 23, 34, 123), parsed);
I have seen several answers to resolve the situation outlined in this question such as using DateTime.Parse, DateTime.ParseExact, or Convert.ToDateTime. I am trying to determine why the problem is seemlingly inconsistent. I built an application using the Microsoft Enterprise Library Software Factory with a SQL Server 2008 R2 backend and it has been in production for about 9 months now. It has at least 20 instances with the same code format that assign DateTime property values from C# to System.Data.DBType.DateTime parameters for stored procedures. 19 of the 20 code blocks work fine. For the 20th I had to add the .ToString() call as shown below to resolve the error mentioned in this question.
db.AddInParameter(command, "beginDT", DbType.DateTime, timeBlock.BeginDT.ToString());
So anyone have some insight on why would it work fine in 19 absolutely identical instances and not in the 20th? I am just trying to get more of an understanding of the inter-relationship of these objects so I can build solid code. I have since gone back to all other instances and added the .ToString() call. Haven't completed my regression testing though; so, I don't know if that was a mistake.

Format DateTime.Now

A peculiar request this one.
I am looking to compare two times in C#.
I have:
DateTime systemDate = DateTime.Now.AddMinutes(-15);
//which I presume subtracts 15 minutes from the current time
I am then reading in an ftp file from a Fedora server containing a date and time that I am reading in as a stream and converting to a DateTime
2011-03-17 09:00:18.000000000 +0000
I then parse this:
compareDate = DateTime.Parse(streamer);
My Question therefore is how do I format systemDate to be in the same format as the one I have parsed in compareDate? I am aware you can format DateTime but all of the sites I have seen so far dont have it in this format.
Thank you in advance, feel free to comment if you think I have missed anything :)
You can do it like this,
DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
No need to format systemDate, because you already parsed the date from the FTP server into a DateTime. You can just compare systemDate with compareDate.
just use var systemDate = DateTime.UtcNow.AddMinutes(-15); for your original one, then you just
if (DateTime.Equals(systemDate, compareDate))
{
//...
}

.NET DateTime to SqlDateTime Conversion

While converting .NET DateTime (when is default(DateTime)) to SqlDateTime should I always check if the .NET date is between SqlDateTime.MinValue and SqlDateTime.MaxValue [or] Is there a good way to do this.
Is it possible that the date could actually be outside that range? Does it come from user input? If the answer to either of these questions is yes, then you should always check - otherwise you're leaving your application prone to error.
You can format your date for inclusion in an SQL statement rather easily:
var sqlFormattedDate = myDateTime.Date.ToString("yyyy-MM-dd HH:mm:ss");
If you are checking for DBNULL, converting a SQL Datetime to a .NET DateTime should not be a problem. However, you can run into problems converting a .NET DateTime to a valid SQL DateTime.
SQL Server does not recognize dates prior to 1/1/1753. Thats the year England adopted the Gregorian Calendar. Usually checking for DateTime.MinValue is sufficient, but if you suspect that the data could have years before the 18th century, you need to make another check or use a different data type. (I often wonder what Museums use in their databases)
Checking for max date is not really necessary, SQL Server and .NET DateTime both have a max date of 12/31/9999 It may be a valid business rule but it won't cause a problem.
Also please remember resolutions [quantum of time] are different.
http://msdn.microsoft.com/en-us/library/system.data.sqltypes.sqldatetime.aspx
SQL one is 3.33 ms and .net one is 100 ns.
on my quest to do this with entitie, i stumbled over here, just hitting back to post what i've found out...
when using EF4, "a sql's" datetime column can be filled from .NET's DateTime using BitConverter.
EntitieObj.thetime = BitConverter.GetBytes(DateTime.Now.ToBinary());
also Fakrudeen's link brought me further... thank you.
-To compare only the date part, you can do:
var result = db.query($"SELECT * FROM table WHERE date >= '{fromDate.ToString("yyyy-MM-dd")}' and date <= '{toDate.ToString("yyyy-MM-dd"}'");
var sqlCommand = new SqlCommand("SELECT * FROM mytable WHERE start_time >= #StartTime");
sqlCommand.Parameters.Add("#StartTime", SqlDbType.DateTime);
sqlCommand.Parameters("#StartTime").Value = MyDateObj;

Categories

Resources