Failed to convert from a String to a TimeSpan error - c#

I am attempting to post to my Database using a SqlCommand like so
queryLogResults.Parameters.Add("#executionTime", SqlDbType.Time).Value = executionTime;
This is the string I am passing in as executionTime
string performanceTime = _stopWatch.Elapsed.ToString("mm':'ss':'fff");
I am assuming it has something to do with the milleseconds because it works only sometimes, and if I post just minutes and seconds it works every time. Am I not using the right type of SqlDbType? In my Database ExecutionTime is a time(7) value.

If you're trying to set a parameter value that's of type SqlDbType.Time, then you shouldn't need to convert it to a string. Just use
TimeSpan performanceTime = _stopWatch.Elapsed;
queryLogResults.Parameters.Add("#executionTime", SqlDbType.Time).Value = performanceTime;

Looks to me like it's the single quotes in format string:
mm':'ss':'fff
Additionally, you need to include Hours as part of the string. Finally, milliseconds are traditionally separated with a decimal point, rather than a colon.
So a better format string looks like this:
HH:mm:ss.fff
Since ADO.Net wants to convert this string value back into a TimeSpan, it needs to be able to the parse the string, and those formatting differences are throwing it off.
Moreover, since ADO.Net will already use a TimeSpan value, I suggest changing the type of the method argument from string to TimeSpan. Then you can pass _stopWatch.Elapsed to the method without converting to a string.
This will also improve performance. Because of the complexity and variety of localization/culture options, converting Date and numeric values to and from strings is surprisingly expensive. You can save your computer some work by avoiding the two conversions in this code.

Related

Parse timestamp without knowing the timezone

I am parsing Timestamps from a JSON into C#. Usually these timestamps look like this: "2017-05-12T14:45:42.7529468Z". However I might receive timestamps from other timezones, e.g. a timestamp from GMT+2 - I assume it would look like this "2017-05-12T16:45:42.7529468B".
I used to parse the timestamps with
DateTime myTimestamp = myJSON.SourceTimestamp
This method doesn't seem to work for timestamps which do not have Z at the end.
Am I assuming the wrong timestamp format for other timezones like GMT+2?
Or do I need a special parser again?
I tried using
DateTime myTimestampExact = DateTime.ParseExact(myJSON.SourceTimestamp, "yyyy'-'MM'-'dd'T'HH':'mm':'ss.ffffffK", null);
however the latter returns me an error:
The best overloaded method match for 'System.DateTime.ParseExact(string, string, System.IFormatProvider)' has some invalid arguments

Removing time part from a string c#

I am trying to remove the time zone from a string.
The string looks like below.
2/05/2018 6:54:00 AM
This data has been retrieved from a local database.
Code Part:
string datCommisioned = (rdr.GetValue(4).ToString());
string dateonly = datCommisioned.ToString("dd/MM/yyyy");
When I tried to execute the above coding it's getting an error,
cannot convert from 'string' to 'System.IFormatProvider'
Any idea how to catch the date part excluding the time? Thanks!
Edit: This is probably not a duplicate question as I refer the other questions before posting. The context of this question is different because the string I'm extracting is not recognised as a valid DateTime (Manually entered by users) thus DateTime class cannot be used.
//Assuming value at index 4 is a DateTime.
string datCommisioned = rdr.GetDateTime(4).ToString(#"dd/MM/yyyy");
It's good practice to use the more specific and strongly typed methods with a DataReader. Helps identify bugs faster.
There are several approaches
Use DateTime object.
DateTime dateTime = DateTime.Parse(datCommissioned);
string dateonly = dateTime.ToString("dd/MM/yyyy");
Split on whitespace
var split = datCommissioned.Split(' ');
string dateonly = split[0];
You just need to change it to be this.
var datCommisioned = DateTime.parse(rdr.GetValue(4)).ToString("dd/MM/yyyy");
You are currently converting it to a string then trying to ToString() the String, when you just need to toString() the date from the reader.
Just another approach here; You can utilize DateTime.Parse() or perhaps a safer alternative, DateTime.TryParse(), to convert the string to a DateTime object. Then, use the Date property of the DateTime object to basically set the time to midnight, ie. 00:00:00. Depending on what you’re using the date for, having the DateTime object instead of a string could be helpful. You can then call ToString(“d”) or use another formatter to give you the date only portion in the desired format.
if (TryParse(datCommissioned, out DateTime commissionedDate))
{
commisionedDate = commisionedDate.Date;
string commissionedDateText = commissionedDate.ToString(“dd/MM/yyyy”);
}

Get and format UTC Time corresponding to NodaTime ZonedDateTime value?

I have ZonedDateTime value. I need to obtain corresponding UTC time and to format it as ISO8601 string (without Time Zone).
What's the right "NodaTime way" of doing it?
I understand that I can use ZonedDateTime.ToDateTimeUtc() method to get .Net DateTime Kind of Utc. Should I do it and then just use ToString()?
Like
var myresult = resZonedDateTime.ToDateTimeUtc().ToString("s")
Should I really use "s" there?
There are a few different ways, depending on exactly what you're looking for.
First, you need to decide whether you want a value like 2014-10-30T16:46:49 or one like 2014-10-30T16:46:49Z. Both are allowed by ISO8601, but the trailing Z at the end is specifically used when the value is UTC. If you send the string elsewhere, the receiving party will not have to guess what the basis for the value is.
If you want the Z, then convert your ZonedDateTime to an Instant using the .ToInstant() method.
Instant instant = zdt.ToInstant();
If you don't want the Z, but still want the value to reflect UTC, then adjust your ZonedDateTime to UTC, then strip it down to the LocalDateTime using it's .LocalDateTime property.
LocalDateTime ldt = zdt.WithZone(DateTimeZone.Utc).LocalDateTime;
Next, you need to decide whether you want to format the string inline with the BCL-based API, or whether you want to use the pattern-based API. Noda Time supports both, which you can read about in the user guide.
The BCL-based API allows you to use methods you're already familiar with, such as .ToString() and .ToString("some format", someCulture) For example:
string s = instant.ToString();
or
string s = ldt.ToString("s", CultureInfo.InvariantCulture);
The pattern-based API separates the work of parsing the format string from doing the actual formatting, as two steps:
var pattern = InstantPattern.ExtendedIsoPattern;
var s = pattern.Format(instant);
It is much more efficient if you are going to be formatting many items. I typically use it when I'm working with LINQ. For example:
var pattern = InstantPattern.GeneralPattern;
var strings = instants.Select(pattern.Format);
or
var pattern = LocalDateTimePattern.GeneralIsoPattern;
var strings = ldts.Select(pattern.Format);
And finally, you need to think about the precision you want. In the pattern API, the "general" formats are precise to whole seconds. The "extended" formats include fractional seconds up to 7 decimal places. You could also create your own pattern using the Create... static methods on the various pattern classes.
If you are just using ToString, then keep in mind that the default format may or may not be what you are looking for. Again, you can pass a format string. For Instant values, "g" is precise to whole seconds, but you would use a custom string of "yyyy'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFF'Z'" if you need precision. For LocalDateTime values, "s" is precise to whole seconds, and "o" is precise to 7 decimals.
Again, all of this is in the "Text" chapter of the user guide, which I would encourage you to read.

Retrieve format of date from date value

I am receiving some data into a variable of type object. In certain cases this data are date values. For that data, I would like to convert this to a string and return it in the same format as it was passed. In some cases, the object could be a datetime, in others a date only or time only values.
As soon as I convert the object to a date or a string, it is obviously given a time of midnight which in my scenario may be a valid time (so I cannot test to see if the time is midnight in which case I could deduce that it would have been a date only date value, nor can I use regex on it as there will always be a time element).
Intellisense shows me it correctly, ie in the format I am wishing to return the value.
Is there an easy way to achieve this (hopefully without using reflection)
Many thx
Simon
Your question is a little unclear but I think you're looking for something like this:
DateTime result;
if (DateTime.TryParse(value, out result))
{
// use result here
}
In the above code value is a string that represents the data coming in. The code will only enter the if block if the string is a valid DateTime. At which point you can do the processing you need on it.
Im not sure i understand the question but i would recommend you to take a look at this conversion example on MSDN, and see the Documentation of the DateTime Structur it contains a lot of Conversion/Formatting Methods i hope it helps.
There are many way to do formatting on the datetime and one of the simple way is fetch the data from the required table in the desired format. Like here you need to display the date and if you your format is dd/MM/yyyy then try this
select Convert(varchar(10),StartDate,103) as StartDateformat from table where filtername=#filtername
use this link to find other format Cast and Convert
From local variable to DateTime Conversion
DateTime todateformat = Convert.ToDateTime(txttodate.Text.Trim());
From DateTime to local variable Conversion in specific format
string startdate = todateformat.ToString("dd/MM/yyyy hh:mm:ss");

C# How to parse a string of date in an arbitrary specified Oracle date format?

How to parse a string of date in an arbitrary specified Oracle date format in C#?
So... the oracle format string is a bit different from the C# datetime format string, so I can't use that format-string as an argument for the parse.
I am using Devart/CoreLab but their OracleDate.Parse seems to be really strange and not working for me. How can I parse it correctly?
Do I have to call a query to the db with a TO_DATE/TO_CHAR just to get a conversion? Or that I have to map each oracle format string element into a C# format string element?
edit: And the format string of Oracle and C# are different, such as MON instead of MMM...
edit2: more clarification:
Basically I would have strings that are oracle-date-in-string, e.g. "08-OCT-85", and I am also able to get the oracle format pattern that these date string is following, such as "DD-MON-YY", "DD-MON-RR", "YYYY/RM/DD"... etc
I would like to be able to parse them into a C# DateTime properly so that I can set them to Parameter (which expects C# DateTime), and the problem is these oracle-date-format-pattern is not the same as the C# DateTime-parse-format-pattern.
I suspect somewhere out there might exist some function that can do something like
DateTime dt = ParseDatestringWithSpecifiedOracleDatePatternIntoCSharpDateTime("08-OCT-85", "DD-MON-YY); right?
But I can't find it yet :(
DateTime.TryParseExact allows you do pass a format string to exactly define the format (or an array of formats to try in turn).
Could you use DateTime.TryParseExact() with a given format string?

Categories

Resources