In my own library I created the function getCurrentTime
. It's a versatile getter and converter of date and time. This function can create dates from timestamps in microseconds. It allows you to create clocks, calendars, countdown timer, etc.
months = "Jan:31;Feb:28;Mar:31;Apr:30;May:31;Jun:30;Jul:31;Aug:31;Sep:30;Oct:31;Nov:30;Dec:31";
function getCurrentTime(unixTimeStamp)
{
if (unixTimeStamp)
{
this.dateObject = new Date(unixTimeStamp);
}
else
{
this.dateObject = new Date();
}
// Time
this.dateObject.h = this.dateObject.getHours();
this.dateObject.m = this.dateObject.getMinutes();
if (this.dateObject.m < 10)
{this.dateObject.m = "0" + this.dateObject.m;}
this.dateObject.s = this.dateObject.getSeconds();
if (this.dateObject.s < 10)
{this.dateObject.s = "0" + this.dateObject.s;}
//Date
this.dateObject.y = parseInt(this.dateObject.getFullYear());
this.dateObject.mo = this.dateObject.getMonth()+1;
if (this.dateObject.mo < 10)
{this.dateObject.mo = "0" + this.dateObject.mo;}
this.dateObject.d = this.dateObject.getDate();
if (this.dateObject.d < 10)
{this.dateObject.d = "0" + this.dateObject.d;}
this.today = this.dateObject.d + "/" + this.dateObject.mo + "/" + this.dateObject.y;
this.now = this.dateObject.d + "/" + this.dateObject.mo + "/" + this.dateObject.y + " " + this.dateObject.h + ":" + this.dateObject.m + ":" + this.dateObject.s;
this.dateStamp = Date.parse(this.dateObject.mo+"/"+this.dateObject.d+"/"+this.dateObject.y);
//these are the objects returned by getCurrentTime() next to hour, minutes, seconds, year, month and date.
this.dateObject.fullDate = this.dateObject.d + " " + months.split(/;/)[this.dateObject.mo-1].split(/:/)[0] + " " + this.dateObject.y;
this.dateObject.timeZoneOffset = dateObject.getTimezoneOffset(); //in minutes.
this.dateObject.today = this.today;
this.dateObject.now = this.now;
this.dateObject.dateStamp = this.dateStamp;
return this.dateObject;
}
timeStamp = <%= ConvertToTimestamp(DateTime.UtcNow).ToString() %>
setInterval(clock, 1000);
function clock()
{
timeStamp += 1000;
var timeObj = getCurrentTime(timeStamp);
var timeString = timeObj.h + ":" + timeObj.m + ":" + timeObj.s;
console.log(timeString);
}
This function without unixTimeStamp
gets the clients time settings, but if you load a date var into it with aspx <%= ConvertToTimestamp(DateTime.UtcNow).ToString() %>
it will update from the time stamp it got. How to retrieve time stamp:
public double ConvertToTimestamp(DateTime value)
{
//create Timespan by subtracting the value provided from
//the Unix Epoch
TimeSpan span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
//return the total milliseconds (which is a UNIX timestamp * 1000)
return (long)span.TotalMilliseconds;
}
http://jsfiddle.net/3Lp4mwpn/ : example
Please note that getCurrentTime
is returning an object with more possibilities than showing time. It can provide you with multiple date formats.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…