Now() Value in Coldfusion

I am trying to set the expression #Now() + CreateTimeSpan('30','0','0','0')# in a cookie and manipulating the values in a JS function.

The value of the expression is being displayed as 41720.406? What does this value mean?

Any pointers would be really helpful.

2

3 Answers

41720.406? What does this value mean?

To answer your question, apparently it represents a number of days from the CF epoch ie 1899-12-30, plus or minus time zone offsets.

 <cfscript>
    cfEpoch  = createDate(1899, 12, 30);

    // add number of whole days ie 41720
    finalDate  = dateAdd("d", 41720, cfEpoch ); 
    // add partial days ie partialDay * millisecondsPerDay
    finalDate  = dateAdd("l", 0.406 * 86400000, finalDate);   

    // Result: Today's date and time plus 30 days
    writeOutput( "finalDate="& dateConvert("local2UTC", finalDate) );
 </cfscript>

Having said that, it is much simpler to use date functions as others suggested, rather than mucking with time span objects.

1

You may want to use DateAdd() instead. So use DateAdd('d', 30, Now()).

<cfset x = DateAdd('d', 30, now())>
<cfoutput>#toScript(x, "time")#</cfoutput>

output:

time = new Date(2014, 2, 22, 2, 36, 26);

Since you mentioned cookies, it's worth pointing out that dates for cookies use a specific format, i.e. Thu, 01-Jan-1970 00:00:01 GMT

This is not how CF formats dates by default - when you output #SomeDate# the format used is {ts '1970-01-01 00:00:01'} instead.

Here's a function that returns a date as a string in the format cookies use:

<cffunction name="formatCookieDate" returntype="String" output=false access="public">
    <cfargument name="DateTime" type="Date"   default=#Now()# />
    <cfargument name="isUtc"    type="String" default=false   />

    <cfif NOT Arguments.isUtc >
        <cfset Arguments.DateTime = DateConvert('local2utc',Arguments.DateTime) />
    </cfif>

    <cfreturn DateTimeFormat( Arguments.DateTime ,'E, dd Mmm yyyy HH:nn:ss' ) & ' GMT' />
</cffunction>

You can use it like this:

formatCookieDate( Now() + 30 )

Whilst some prefer using DateAdd, it is perfectly valid to add days directly - though you might want to consider if you're actually wanting to add 30 days versus adding 1 month.

NOTE: On versions prior to CF10 you'll need to split the DateTimeFormat into DateFormat and TimeFormat and update the masks accordingly.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest