JavaScript @Now Equivalent

Jake Howlett, 6 December 2000

Category: JavaScript; Keywords: date time

Have you ever needed to set a field's value to the current time? Probably. Just put @Now in the Default Value event of the field. But, this is the time that the server thinks it is! What if you want to know the time your user is on.

Consider the notes.net café. When I create a document it says it was at the time the server is on, not me. So it's a lie really. That's not when *I* created it. Would it not be more useful if you knew the time that somebody replied to you in their time? I think so.

The only way to do this is to use Client-Side JavaScript. The following function returns a string in the format:

"dd/mm/yyyy hh:mm:ss"
(or "mm/dd" if it is required in that format).

You can call it from a hyper-link that the user clicks, in the onLoad event of the form or when the user submits the form. It's up to you and your requirements...

<script>
/*
I've used the arguments property of a JavaScript
function, not because I had to, but just to so as to
show you all how. The arguments[] are:
[0] DateFormat = Whether it is mm/dd or dd/mm (string)
[1] TargetField = Where to put the returned value (object)
*/
function getDateTimeNow(){
nw = new Date(); //Now !
mt = nw.getMonth() +1; //getMonth() is zero based !
mt = (mt < 10) ? "0" + mt : mt;
dy = nw.getDate();
dy = (dy < 10) ? "0" + dy : dy;
yr = nw.getYear();
hr = nw.getHours();
hr = (hr < 10) ? "0" + hr : hr;
mn = nw.getMinutes();
mn = (mn < 10) ? "0" + mn : mn;
sc = nw.getSeconds();
sc = (sc < 10) ? "0" + sc : sc;

ret = (arguments[0].toLowerCase().charAt(0) == "d") ? dy +"/"
+ mt : mt + "/" + dy;
ret += "/" + yr + " " + hr + ":" + mn + ":" + sc;

arguments[1].value = ret;
}</script>


Test it out here:


Set Date/Time (dd/mm)
Set Date/Time (mm/dd)


It is important to get the "dd/mm" format correct so as to avoid errors/confusion. If you are NOT 100% percent sure what it will be then use this method to find out. The function call would then look something like:

<a href="JavaScript:getDateTimeNow(document.forms[0].DateFormat.value , document.forms[0].NowDateTime);">Set Date</a>




Note: If you know a bit of JavaScript you may be wondering why I'm not just using built in calls like toLocaleString(). Having tried these I've found that what they return depends on OS and browser type/version. This method will always return dates in the format that the Notes server expects.