How to format DateTime using model binding - asp.net

I am using entity framework in an asp.net web forms application, and binding my model using code nuggets / directives. I have a DateTime field -ClosedDate- and I am trying to display the hours between that and the current date and time, which represents the remaining hours. The value it produces without formatting it is correct, I just want to change the format.
For 2 hours and 30 minutes remaining, it is displayed as 2.50000000000000, and I would like it displayed as either 2 or 2.5. I tried toString() with custom format strings, but could not get the correct value
The Code
<%# Item.ClosedDate.Subtract(DateTime.Now).TotalHours%>
This produces 2.50000000000000
<%# Item.ClosedDate.Subtract(DateTime.Now).TotalHours.ToString("hh")%>
This produces hh
<%# Item.ClosedDate.Subtract(DateTime.Now).ToString("hh")%>
This produces 02, which is fine, but when ClosedDate is greater than 24 hours, the value is not correct.
When ClosedDate = 2013-12-10 01:10:25.000 and DateTime.Now = 2013-12-07 20:20:00.000, the value produced was 04.
When ClosedDate = 2013-12-10 19:54:11.000 and DateTime.Now = 2013-12-07 20:20:00.000, the value produced was 23.

A couple of things here. This:
Item.ClosedDate.Subtract(DateTime.Now).TotalHours
returns a double, and this:
Item.ClosedDate.Subtract(DateTime.Now)
returns a TimeSpan, not a DateTime.
So, you've been trying to format a double or a TimeSpan as an hour "hh", but the time and date format specifiers should only be used with DateTime structs. If you just want the difference in hours with a specific number of decimal places, use a built-in or custom number format that will pad your result, such as:
Item.ClosedDate.Subtract(DateTime.Now).TotalHours.ToString("#0.##");
The above should display 2.5 as 2.5, and 2.0 as 2.
See the Standard Numeric Format Strings and Custom Numeric Format Strings documentation on MSDN for more examples.

Related

DateTime format for 9/14/2016 19:31

I am doing an F# course by Richard Broida. In one lecture I am supposed to parse a CSV document. Everything works fine except for parsing datetime. My local culture settings are Slovak (sk-SK) and I am trying to parse the following datetime string:
9/14/2016 19:31
I have read through the CSV file and found out that months, days and hours can all have both one or two digits. Years always have 4 digits and minutes always have 2 digits. So, the datetime 10/7/2016 9:01 is also a valid one.
I have created an adapter function:
let dateTimeParseAdapter format provider date =
DateTime.ParseExact(date, format, provider)
and then called
dateTimeParseAdapter "M/d/yyyy h:mm" CultureInfo.InvariantCulture "9/14/2016 19:31"
but I got an exception message saying
System.FormatException: String was not recognized as a valid DateTime.
I tried adjusting the format string to exactly match the number of digits in my single date. However, even the following code resulted in the same error message.
dateTimeParseAdapter "M/dd/yyyy hh:mm" CultureInfo.InvariantCulture "9/14/2016 19:31"
Why am I getting the exception message? Should I change the CultureInfo settings? Or is there a pre-defined datetime format to parse my datetimes?
When working with 24 hour format you should use H (HH) not h hh (which is for 12 hour format) pattern:
format = #"M/d/yyyy H:mm";
since you are using 24 hour in your value you must put capitals in hours. Change
"M/dd/yyyy hh:mm"
to
"M/dd/yyyy HH:mm"

Different dates in SSRS report with same calculation

So I've got what could be a very silly question, but for some reason my 'problem' isn't working.
It's quite simple really. One of the fields in a SSRS tablix is a due date calculated by using the SQL function DateAdd:
=DateAdd(DateInterval.Day, (Int(Fields!TMinus.Value) * 7), Parameters!StartDate.Value)
Where TMinus is a negative integer simulating weeks and StartDate being the date the activity started.
I'm calculating the same thing in VB.NET using this formula to set up the DueDate of an activity in a row cell:
Dim intTMinus As Integer = CInt(dataItem.GetDataKeyValue("TMinus").ToString)
CType(dataItem.FindControl("RlblDue"), RadLabel).Text = CDate(DateAdd(DateInterval.Day, (intTMinus * 7), dtStartDate)).ToString
The problem is that the SSRS report shows a DIFFERENT date than the Grid, even though I've used hardcoded values to attempt to find the culprit in the report.
This calculation in the report:
=DateAdd(DateInterval.Day, (Int(-40) * 7), '12/09/2016')
Shows the date: 07/12/2015 in the Grid, but 3/4/2016 on the Report
Note DateAdd arguments data types have to be DateInterval, Double, and DateTime respectively. You are passing a string '12/09/2016' for the third argument but it requires a DateTime. By the way, strings in SSRS must be surrounded with double quotes.
After fix the expression, it should be like this:
=DateAdd(DateInterval.Day, (Int(-40) * 7), CDATE("2016-09-12"))
Which returns: 07/12/2015 as your Grid in VB.
Note CDATE("2016-09-12") converts the date string in a DateTime value.
Check your parameter is set to Date/Time type.
REFERENCE
Let me know if this helps.

ASP.NET "String was not recognized as a valid DateTime."

First off, I realize there's a million pages discussing this already. I have looked at least a hundred of them but cannot seem to make this work. My date and time is presented as a string, compiled from javascript to grab client's local time. It is formatted like this: 7/11/2015 8:34 PM.
I currently have:
Dim datetimeformated = DateTime.ParseExact(lblDateTime.Text, "MM/dd/yyyy HH:mm tt", CultureInfo.InvariantCulture)
I have tried many different variants, but this should be correct I think, yet it does not work. Any help is greatly appreciated. TIA
The correct format for your case is: M/dd/yyyy h:mm tt, and perhaps even, M/d/yyyy h:mm tt, if you can have the day of the month as a single digit.
Explanation: Why your format string didn't work.
MM: means that you must always have 2 digits for the month, clearly not the case in your example.
dd: again, means that you must always have 2 digits for the day of the month. Is that the case? Adjust the parameter if needed.
HH: This actually means that you are expecting the hour value as 2-digits using the 24-hour clock (00-23), which is clearly wrong on both accounts. You can have a single digit, and you are not using the 24-hour clock, because you are using the AM/PM designator.
Relevant documentation link: Custom Date and Time Format Strings.

ColdFusion - DateTime Format with GMT offset

I am using ColdFusion 10 to make some REST calls and the date returned is using a GMT offset.
Example: 2013-03-25T14:30:40-04:00
I need this formatted for 2 purposes:
Screen Display so it looks something like mm/dd/yyyy hh:mm:ss
To Insert into mySQL.
I have tried a variety of the CF time/date functions but continue to get the "is not a valid date format"
I thought maybe the #ParseDateTime(i.submitted_at,"pop")# would handle it with POP but same issue.
Spent a few hours now trying multiple variations and googling around now just going in circles. Any ideas would be greatly appreciated.
Thanks!
Have a look at the UDF DateConvertISO8601() on CFLib.
DateConvertISO8601(ISO8601dateString, targetZoneOffset) on CFLib
Description:
This function take a string that holds a date in ISO 8601 and converts it to ODBC datetime, but could be adapted to convert to whatever you like. It also will convert to a datetime in a timezone of your choice by specifying the offset, i.e. it could take a datetime in GMT and convert to PT. See http://www.w3.org/TR/NOTE-datetime for description of ISO 8601, the International Standard for the representation of dates and times.
Return Values:
Returns a datetime.
The source code is viewable at the link I provided.
This, 2013-03-25T14:30:40-04:00, is a string. If you run this:
x = left(2013-03-25T14:30:40-04:00, 19);
you get 2013-03-25T14:30:40. You can use the replace function to replace the T with a space. You can then to this
DateTimeVar =parsedatetime('2013-03-25 14:30:40');
Now you have a datetime variable that you can format. If necessary you can do a datediff with the offset from GMT.
This is an informational answer, not a direct answer to the question.
ColdFusion 11 has updated the ParseDateTime() function so that it will correctly convert the ISO-8601 date/time strings to a ColdFusion datetime object.
With a number of remote requests and responses, the date / time values can often be returned in ISO format. In your case, the mask looks like this:
YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
In this ISO format, the T string is a literal representation of a marker where the time stamp starts in the string (with the offset following directly).
Below is a reusable function that will convert an ISO date format into a useable ColdFusion date time object:
<cffunction name="ISOToDateTime" access="public" returntype="string" output="false"
hint="Converts an ISO 8601 date/time stamp with optional dashes to a ColdFusion
date/time stamp.">
<cfargument name="Date" type="string" required="true" hint="ISO 8601 date/time stamp." />
<cfreturn ARGUMENTS.Date.ReplaceFirst(
"^.*?(\d{4})-?(\d{2})-?(\d{2})T([\d:]+).*$",
"$1-$2-$3 $4"
) />
</cffunction>
You can then call the function like so to output or return a ColdFusion-friendly version of the date time:
ISOToDateTime( "2013-03-25T14:30:40-04:00" )
That function is courtesy of Ben Nadel. The original blog post can be found here:
http://www.bennadel.com/blog/811-Converting-ISO-Date-Time-To-ColdFusion-Date-Time.htm
You can also convert the date time value using the offset, if required. Again, Ben Nadel has a great blog post outlining how to accomplish this:
http://www.bennadel.com/blog/1595-Converting-To-GMT-And-From-GMT-In-ColdFusion-For-Use-With-HTTP-Time-Stamps.htm
CF10 can use this code as stated in the example of the parseDateTime() doc.
<cfset string = "1997-07-16T19:20:30+01:00">
<cfset date = parseDateTime(string, "yyyy-MM-dd'T'HH:mm:ssX")>

DateTime format conversion to string ignores AM/PM

I am trying to convert DateTime object to string using formatting but due to some strange reason, it ignores AM/PM. It would just take the magnitude of the Hour in the object.
I am using the following format:
StartDate.ToString("yyyy-MM-dd hh:mm:ss.fff");
and
String.Format("0:yyyy-MM-dd hh:mm:ss.fff", StartDate);
I don't think that there is a difference between the two, but just wanted to give it a try. If I pass a value 4/28/2012 6:00:00 AM or 4/28/2012 6:00:00 PM, the result is the same "2012-04-27 06:00:00.000"
You've used hh which uses the 12-hour clock. You want HH which uses the 24-hour clock.
See MSDN for more details about custom format strings.
Note that you may wish to specify the invariant culture, unless you really want the time separator to depend on the current culture:
string formatted = StartDate.ToString("yyyy-MM-dd HH:mm:ss.fff",
CultureInfo.InvariantCulture);
(Note that you shouldn't have the braces if you're passing the format string to ToString. I'll assume this was just a typo in the question.)
If you want to use the 12-hour clock, use tt in the format string to produce the AM/PM designator.

Resources