Before I move on to examples, just a quick reference to one more important concept: epoch. It is defined as time kept internally by a computer system, expressed as the number of time units that have elapsed since a specified date. Unix time epoch, used by UNIX, Linux, other UNIX-like systems, Mac OS X, as well as Java, JavaScript, C and PHP Programming languages, started on January 1, 1970 and is usually expressed in milliseconds. The epoch is what makes time related calculations so simple…
You can find many example of various JavaScript time functions by simply “googling” the term however, there is not much practical information on how to apply them. Here are a few transformations I found very useful:
Current date and time
Date() function, in its simplest form, will return current date and time as displayed on user computer.
var localtime= new Date();
// returns eg. Mon Nov 9 18:37:46 UTC+1100 2009
I often use a “combination” shown below to time stamp dynamic data (eg. frequently updated RSS feeds) in order to prevent caching so the information cannot be recalled from a local browser cache but is always called directly from the source:
var o= new Date();
var p= o.getTime();
Then I add dynamically extra parameter to source data URL :
var url= “somepage.html?p=”+p;
It is simpler than trying to get all “no-cache” headers and metatags to work consistently in all browsers.
Date and time in the past
By adding an additional parameter, the same Date() function can be used to convert a string of letters to a proper date format (ie. any date, expressed in “local time”):
var localtime= new Date(“Fri, 06 Nov 2009 04:56:00”);
// returns Fri Nov 6 04:56:00 UTC+1100 2009
Past date and time in GMT
Any past date expressed in local time can be easily converted to GMT.
var localtime= new Date(“Fri, 06 Nov 2009 04:56:00”);
var gmt=localtime.toUTCString();
// returns: Thu, 5 Nov 2009 17:56:00 UTC
GMT to local time
Reverse conversion from GMT to local time is also very easy. If your input time is expressed in GMT and you need local equivalent, just include “GMT” letters in the code to flag the input is not a local time!
var localtime= new Date(“Fri, 06 Nov 2009 04:56:00 GMT”); or
var localtime= new Date(“2009/11/05 04:56:00 GMT”);
// returns Fri Nov 6 15:56:00 UTC+1100 2009
Time in milliseconds (epoch)
Epoch is a very handy format for storing time info in a database and for all sorts of time related calculations.
var fulldate= new Date(); //returns local time as set on the user computer
var epoch=fulldate.getTime(); // converted to milliseconds
Unfortunately, I could not find any information on acceptable date formats. For example, this very frequently used Unix format does not work in JavaScript Date() function: “2009/11/06T03:42:40Z” - it has to be converted to a format that JavaScript can recognise before use.
No comments:
Post a Comment