Show current date - javascript

I am using the following to get the current date:-
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1;
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var newdate = day + "/" + month + "/" + year;
If I alert(newdate); it shows:-
3/06/2013
Is there any way I can display this as:-
03/06/2013

With plain Javascript, only manually
if (day < 10) day = "0" + day;
if (month < 10) month = "0" + month;

If you want to avoid using a library, and don't mind an extra line in your JavaScript:
var day = dateObj.getUTCDate(),
dd = parseInt(day, 10) < 10 ? '0' + day : day;

Using JQuery DateFormat:
$.format.date(dateObj.toString(), "dd/MM/yyyy");

var mydate=new Date();
alert(mydate.toString('dd/MM/yyyy'));

function padWithZeroes(number, width)
{
while (number.length < width)
number = '0' + number;
return number;
}
Now call day = padWithZeroes(day, 2) (and likewise for the month) before you use it.

You can split it and create your own format:
var splitTime = newDate.split("/");
var day = splitTime[0];
var month = splitTime[1];
var year = splitTime[2];
if (day < 10){
day = "0" + day;
}
var myDate = day + '/' + month + '/' + year;
Living demo:
http://jsfiddle.net/rtqpp/

Please use the following:
var dateObj = new Date();
var month = ('0' + (dateObj.getUTCMonth() + 1) ).slice( -2 );;
var day = ('0' + (dateObj.getUTCDate() + 1) ).slice( -2 );
var year = dateObj.getUTCFullYear();
var newdate = day + "/" + month + "/" + year;

Related

How to alert current date in yyyy-mm-dd hrs:min:sec format in javascript?

In my program i need to alert current date with time in specific format(2015-11-18 12:23:00) so i am write like this
var date = new Date();
alert(date);
but the result is Wed Nov 18 2015 12:24:28 GMT+0530 (India Standard Time).
and also i am try like this
<script>
var d = new Date();
var c = new Date();
alert(formatDate(c));
alert(formatDate(d));
function formatDate(d)
{
var month = d.getMonth();
var day = d.getDate();
var hours = d.getHours();
var minutes = d.getMinutes();
month = month + 1;
month = month + "";
if (month.length == 1)
{
month = "0" + month;
}
day = day + "";
if (day.length == 1)
{
day = "0" + day;
}
hour = hour + "";
if (hour.length == 1)
{
hour = "0" + hour;
}
minute = minute + "";
if (minute.length == 1)
{
minute = "0" + minute;
}
return d.getFullYear()+month + '' + day + ''+ hour + '' + minute + '';
}</script>
it is also not working properly.
how can i do this in javascript and also i need to passed the veriable to database in another php file. please help me how can i do this
I think this below code are helpful us.
function getDateTimeFormate () {
now = new Date();
year = "" + now.getFullYear();
month = "" + (now.getMonth() + 1); if (month.length == 1) { month = "0" + month; }
day = "" + now.getDate(); if (day.length == 1) { day = "0" + day; }
hour = "" + now.getHours(); if (hour.length == 1) { hour = "0" + hour; }
minute = "" + now.getMinutes(); if (minute.length == 1) { minute = "0" + minute; }
second = "" + now.getSeconds(); if (second.length == 1) { second = "0" + second; }
return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
}
To get date time formate like.
alert(getDateTimeFormate());
// example alert message: 2011-05-18 15:20:12
Try this..
<script>
var currentdate = new Date();
var datetime = currentdate.getFullYear() + "-"
+ (currentdate.getMonth()+1) + "-"
+ currentdate.getDate() + " "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
alert(datetime);
</script>
Output:2015-11-18 12:46:52
Demo:http://js.do/code/73749
Please try the following code:
Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}
var d = new Date;
function formatDate(d){
dformat = [ (d.getMonth()+1).padLeft(),
d.getDate().padLeft(),
d.getFullYear()].join('-')+
' ' +
[ d.getHours().padLeft(),
d.getMinutes().padLeft(),
d.getSeconds().padLeft()].join(':');
return dformat;
}
alert(formatDate(d));
It will return : 11-18-2015 12:17:02. And to pass the value to a php code check this: How to pass JavaScript variables to PHP?
This might be useful
Date.prototype.yyyy = function() {
var yy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString();
var dd = this.getDate().toString();
var hh = this.getHours().toString();
var min = this.getMinutes().toString();
var ss = this.getSeconds().toString();
return yy +"-" +(mm[1]?mm:"0"+mm[0]) + "-" +(dd[1]?dd:"0"+dd[0])+" "+(hh[1]?hh:"0"+hh[0])+":"+(min[1]?min:"0"+min[0])+":"+(ss[1]?ss:"0"+ss[0]);
};
d = new Date();
d.yyyy();
From the below function you will get all the details you want to show use it according to your need
getMonth() - Returns a zero-based integer (0-11) representing the month of the year.
getDate() - Returns the day of the month (1-31).
getDay() - Returns the day of the week (0-6). 0 is Sunday, 6 is Saturday.
getHours() - Returns the hour of the day (0-23).
getMinutes() - Returns the minute (0-59).
getSeconds() - Returns the second (0-59).
getMilliseconds() - Returns the milliseconds (0-999).
getTimezoneOffset() - Returns the number of minutes between the machine local time and UTC.
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd
}
if(mm<10){
mm='0'+mm
}
var today = dd+'/'+mm+'/'+yyyy;
document.getElementById("DATE").value = today;
Use this code:
var sec = d.getSeconds();
return d.getFullYear()+'-'+month + '-' + day + ' '+ hour + ':' + minute + ':'+sec;
instead of:
return d.getFullYear()+month + '' + day + ''+ hour + '' + minute + '';

Add day(s) in a date in Javascript

I have textbox displaying date and have a button. the function in button is to add 7 days and display in textbox. my code:
function onNext() {
var startdate = document.getElementById('date').value;
var addday = new Date(startdate);
var dd = addday.getDate() + 7;
var mm = addday.getMonth() + 1;
var y = addday.getFullYear();
var displaydate = y + '/' + mm + '/' + dd;
document.getElementById('date').value = displaydate ;
}
The issue how to add a day to go to the next month.
Example the date in Textbox is 2014/08/25 when I click the button the date will be 2014/09/01
Just add 7 days to your date, date already handles change of month/year:
function onNext() {
var startdate = document.getElementById('date').value;
var addday = new Date(startdate);
addday.setDate(addday.getDate() + 7);
var dd = addday.getDate() + 7;
var mm = addday.getMonth() + 1;
var y = addday.getFullYear();
var displaydate = y + '/' + mm + '/' + dd;
document.getElementById('date').value = displaydate ;
}
If you just do this
var dd = addday.getDate() + 7;
var mm = addday.getMonth() + 1;
var y = addday.getFullYear();
that means if date is 21.12.2014 the output will be 28.13.2014
function onNext() {
var startdate = document.getElementById('date').value;
var d2 = new Date(startdate);
d2.setMonth(d2.getMonth()+1);
d2.setDate(1); // you can set here whatever date you want
document.getElementById('date').value = d2.getFullYear() + '/' + d2.getMonth() + '/' + d2. getDate();
}
Use this function
function updateAb(s){//format dd/mm/yyyy chnage according to your need
var dmy = s.split("/");
var joindate = new Date(
parseInt(dmy[2], 10),
parseInt(dmy[1], 10) - 1,
parseInt(dmy[0], 10)
);
var data_days=7;
joindate.setDate(joindate.getDate() + data_days);
var cc=("0" + joindate.getDate()).slice(-2) + "/" +("0" + (joindate.getMonth() + 1)).slice(-2) + "/" +joindate.getFullYear();
document.getElementById("datepickerdisabled1").value=cc;
}

javascript date format conversion [duplicate]

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 9 years ago.
I am using pikaday's datepicker. It gives me output "Fri Sep 20 2013". How can I convert this date into yyyy-mm-dd format and I also would want following date of this selected date and set that one to another element.
I tried this code
function formattedDate() {
var fromdate = new Date(document.getElementById('datepicker').value);
var dd = fromdate.getDate();
var mm = fromdate.getMonth()+1; //January is 0!
var yyyy = fromdate.getFullYear();
if(dd < 10)
{
dd = '0'+ dd;
}
if(mm < 10)
{
mm = '0' + mm;
}
var fromdate1 = dd+'/'+mm+'/'+yyyy;
fromdate.setDate(fromdate.getDate() + 2);
document.getElementById('datepicker').value = fromdate1;
var newdate = fromdate;
document.getElementById('datepicker1').value = newdate;
//alert(newdate1);
}
But it doesn't work.
var date = new Date(dateString);
var year = date.getFullYear(), month = (date.getMonth() + 1), day = date.getDate();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var properlyFormatted = "" + year + month + day;
Or
var date = new Date(dateString);
var properlyFormatted = date.getFullYear() + ("0" + (date.getMonth() + 1)).slice(-2) + ("0" + date.getDate()).slice(-2);
Use momentjs — it's a library available for using in browser and node projects
In your case you should use this pattern:
moment().format("YYYY-mm-D");
And you can try it in console on momentjs's site:

Getting current date and time in JavaScript

I have a script that prints the current date and time in JavaScript, but the DATE is always wrong. Here is the code:
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDay() + "/" + currentdate.getMonth()
+ "/" + currentdate.getFullYear() + " # "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
It should print 18/04/2012 15:07:33 and prints 3/3/2012 15:07:33
.getMonth() returns a zero-based number so to get the correct month you need to add 1, so calling .getMonth() in may will return 4 and not 5.
So in your code we can use currentdate.getMonth()+1 to output the correct value. In addition:
.getDate() returns the day of the month <- this is the one you want
.getDay() is a separate method of the Date object which will return an integer representing the current day of the week (0-6) 0 == Sunday etc
so your code should look like this:
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/"
+ (currentdate.getMonth()+1) + "/"
+ currentdate.getFullYear() + " # "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
JavaScript Date instances inherit from Date.prototype. You can modify the constructor's prototype object to affect properties and methods inherited by JavaScript Date instances
You can make use of the Date prototype object to create a new method which will return today's date and time. These new methods or properties will be inherited by all instances of the Date object thus making it especially useful if you need to re-use this functionality.
// For todays date;
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
// For the time now
Date.prototype.timeNow = function () {
return ((this.getHours() < 10)?"0":"") + this.getHours() +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() +":"+ ((this.getSeconds() < 10)?"0":"") + this.getSeconds();
}
You can then simply retrieve the date and time by doing the following:
var newDate = new Date();
var datetime = "LastSync: " + newDate.today() + " # " + newDate.timeNow();
Or call the method inline so it would simply be -
var datetime = "LastSync: " + new Date().today() + " # " + new Date().timeNow();
To get time and date you should use
new Date().toLocaleString();
>> "09/08/2014, 2:35:56 AM"
To get only the date you should use
new Date().toLocaleDateString();
>> "09/08/2014"
To get only the time you should use
new Date().toLocaleTimeString();
>> "2:35:56 AM"
Or if you just want the time in the format hh:mm without AM/PM for US English
new Date().toLocaleTimeString('en-US', { hour12: false,
hour: "numeric",
minute: "numeric"});
>> "02:35"
or for British English
new Date().toLocaleTimeString('en-GB', { hour: "numeric",
minute: "numeric"});
>> "02:35"
Read more here.
For true mysql style output use this function below: 2019/02/28 15:33:12
If you click the 'Run code snippet' button below
It will show you an simple realtime digital clock example
The demo will appear below the code snippet.
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
month = '0'+month;
}
if(day.toString().length == 1) {
day = '0'+day;
}
if(hour.toString().length == 1) {
hour = '0'+hour;
}
if(minute.toString().length == 1) {
minute = '0'+minute;
}
if(second.toString().length == 1) {
second = '0'+second;
}
var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second;
return dateTime;
}
// example usage: realtime clock
setInterval(function(){
currentTime = getDateTime();
document.getElementById("digital-clock").innerHTML = currentTime;
}, 1000);
<div id="digital-clock"></div>
Just use:
var d = new Date();
document.write(d.toLocaleString());
document.write("<br>");
Short
I develop Steve answer to get exactly what OP need
new Date().toLocaleString().replace(',','')
console.log(new Date().toLocaleString().replace(',',''));
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/"+(currentdate.getMonth()+1)
+ "/" + currentdate.getFullYear() + " # "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
Change .getDay() method to .GetDate() and add one to month, because it counts months from 0.
This should do the trick:
function dateToString(date) {
var month = date.getMonth() + 1;
var day = date.getDate();
var dateOfString = (("" + day).length < 2 ? "0" : "") + day + "/";
dateOfString += (("" + month).length < 2 ? "0" : "") + month + "/";
dateOfString += date.getFullYear();
return dateOfString;
}
var currentdate = new Date();
var datetime = "Last Sync: ";
datetime += dateToString(currentdate );
datetime += + currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
Basic JS (good to learn): we use the Date() function and do all that we need to show the date and day in our custom format.
var myDate = new Date();
let daysList = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
let monthsList = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Aug', 'Oct', 'Nov', 'Dec'];
let date = myDate.getDate();
let month = monthsList[myDate.getMonth()];
let year = myDate.getFullYear();
let day = daysList[myDate.getDay()];
let today = `${date} ${month} ${year}, ${day}`;
let amOrPm;
let twelveHours = function (){
if(myDate.getHours() > 12)
{
amOrPm = 'PM';
let twentyFourHourTime = myDate.getHours();
let conversion = twentyFourHourTime - 12;
return `${conversion}`
}else {
amOrPm = 'AM';
return `${myDate.getHours()}`}
};
let hours = twelveHours();
let minutes = myDate.getMinutes();
let currentTime = `${hours}:${minutes} ${amOrPm}`;
console.log(today + ' ' + currentTime);
Node JS (quick & easy): Install the npm pagckage using (npm install date-and-time), then run the below.
let nodeDate = require('date-and-time');
let now = nodeDate.format(new Date(), 'DD-MMMM-YYYY, hh:mm:ss a');
console.log(now);
Short and simple:-
console.log(new Date().toLocaleString());
Reference
I have found the simplest way to get current date and time in JavaScript from here - How to get current Date and Time using JavaScript
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var CurrentDateTime = date+' '+time;
getDay() gets the day of the week. 3 is Wednesday. You want getDate(), that will return 18.
Also getMonth() starts at 0, you need to add 1 to get 4 (April).
DEMO: http://jsfiddle.net/4zVxp/
You need to use getDate() to get the date part. The getDay() function returns the day number (Sunday = 0, Monday = 1...), and the getMonth() returns a 0 based index, so you need to increment it by 1.
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/"+ (parseInt(currentdate.getMonth()) + 1)
+ "/" + currentdate.getFullYear() + " # "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
const date = new Date()
console.log(date.toLocaleTimeString("en-us", {timeStyle: "medium"})) // Only Time
console.log(date.toLocaleString()) // For both Date and Time
For Documentation
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
+ ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
.getSeconds()) : (now.getSeconds())));
}
get current date and time
var now = new Date();
var datetime = now.getFullYear()+'/'+(now.getMonth()+1)+'/'+now.getDate();
datetime += ' '+now.getHours()+':'+now.getMinutes()+':'+now.getSeconds();
This question is quite old and the answers are too. Instead of those monstrous functions, we now can use moment.js to get the current date, which actually makes it very easy. All that has to be done is including moment.js in our project and get a well formated date, for example, by:
moment().format("dddd, MMMM Do YYYY, h:mm:ss a");
I think that makes it way easier to handle dates in javascript.
.getDay returns day of week. You need .getDate instead.
.getMonth returns values from 0 to 11. You'll need to add 1 to the result to get "human" month number.
This little code is easy and works everywhere.
<p id="dnt"></p>
<script>
document.getElementById("dnt").innerHTML = Date();
</script>
there is room to design
function UniqueDateTime(format='',language='en-US'){
//returns a meaningful unique number based on current time, and milliseconds, making it virtually unique
//e.g : 20170428-115833-547
//allows personal formatting like more usual :YYYYMMDDHHmmSS, or YYYYMMDD_HH:mm:SS
var dt = new Date();
var modele="YYYYMMDD-HHmmSS-mss";
if (format!==''){
modele=format;
}
modele=modele.replace("YYYY",dt.getFullYear());
modele=modele.replace("MM",(dt.getMonth()+1).toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("DD",dt.getDate().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("HH",dt.getHours().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("mm",dt.getMinutes().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("SS",dt.getSeconds().toLocaleString(language, {minimumIntegerDigits: 2, useGrouping:false}));
modele=modele.replace("mss",dt.getMilliseconds().toLocaleString(language, {minimumIntegerDigits: 3, useGrouping:false}));
return modele;
}
dt= new Date();
alert(dt.toISOString().substring(8,10) + "/" +
dt.toISOString().substring(5,7)+ "/" +
dt.toISOString().substring(0,4) + " " +
dt.toTimeString().substring(0,8))
var datetime = new Date().toLocaleString().slice(0,9) +" "+new Date(new Date()).toString().split(' ')[4];
console.log(datetime);
I think i am very late to share my answer, but i think it will be worth.
function __getCurrentDateTime(format){
var dt=new Date(),x,date=[];
date['d']=dt.getDate();
date['dd']=dt.getDate()>10?dt.getDate():'0'+dt.getDate();
date['m']=dt.getMonth()+1;
date['mm']=(dt.getMonth()+1)>10?(dt.getMonth()+1):'0'+(dt.getMonth()+1);
date['yyyy']=dt.getFullYear();
date['yy']=dt.getFullYear().toString().slice(-2);
date['h']=(dt.getHours()>12?dt.getHours()-12:dt.getHours());
date['hh']=dt.getHours();
date['mi']=dt.getMinutes();
date['mimi']=dt.getMinutes()<10?('0'+dt.getMinutes()):dt.getMinutes();
date['s']=dt.getSeconds();
date['ss']=dt.getSeconds()<10?('0'+dt.getSeconds()):dt.getSeconds();
date['sss']=dt.getMilliseconds();
date['ampm']=(dt.getHours()>=12?'PM':'AM');
x=format.toLowerCase();
x=x.indexOf('dd')!=-1?x.replace(/(dd)/i,date['dd']):x.replace(/(d)/i,date['d']);
x=x.indexOf('mm')!=-1?x.replace(/(mm)/i,date['mm']):x.replace(/(m)/i,date['m']);
x=x.indexOf('yyyy')!=-1?x.replace(/(yyyy)/i,date['yyyy']):x.replace(/(yy)/i,date['yy']);
x=x.indexOf('hh')!=-1?x.replace(/(hh)/i,date['hh']):x.replace(/(h)/i,date['h']);
x=x.indexOf('mimi')!=-1?x.replace(/(mimi)/i,date['mimi']):x.replace(/(mi)/i,date['mi']);
if(x.indexOf('sss')!=-1){ x=x.replace(/(sss)/i,date['sss']); }
x=x.indexOf('ss')!=-1?x.replace(/(ss)/i,date['ss']):x.replace(/(s)/i,date['s']);
if(x.indexOf('ampm')!=-1){ x=x.replace(/(ampm)/i,date['ampm']); }
return x;
}
console.log(__getCurrentDateTime()); //returns in dd-mm-yyyy HH:MM:SS
console.log(__getCurrentDateTime('dd-mm-yyyy')); //return in 05-12-2016
console.log(__getCurrentDateTime('dd/mm*yyyy')); //return in 05/12*2016
console.log(__getCurrentDateTime('hh:mimi:ss')); //return in 13:05:30
console.log(__getCurrentDateTime('h:mi:ss ampm')); //return in 1:5:30 PM
I needed to figure this out for a slate in after effects. Here's what I came up with after taking elements from a few different sources -- Formatting is MM/DD/YYYY HH:MM AM/PM
D = new Date(Date(00));
M = D.getMonth()+1;
H = D.getHours();
Mi = D.getMinutes();
N = "AM"
if (H >= 12)
N = "PM"
if (H > 12)
{
H = H-12
}
amtOfZeroes = 2;
isNeg = false;
if (M < 0)
{
M = Math.abs(M);
isNeg = true;
}
Mo = Math.round(M) + "";
while(Mo.length < amtOfZeroes)
{
Mo = "0" + Mo;
}
if (isNeg)
Mo = "-" + Mo;
if (H < 0)
{
H = Math.abs(H);
isNeg = true;
}
Ho = Math.round(H) + "";
while(Ho.length < amtOfZeroes)
{
Ho = "0" + Ho;
}
if (isNeg)
Ho = "-" + Ho;
if (Mi < 0)
{
Mi = Math.abs(Mi);
isNeg = true;
}
Min = Math.round(Mi) + "";
while(Min.length < amtOfZeroes)
{
Min = "0" + Min;
}
if (isNeg)
Min = "-" + Min;
T = Ho + ":" + (Min)
Mo + "/" + D.getDate() + "/" + D.getFullYear() + " " + T + " " + N
If someone is in search of function
console.log(formatAMPM());
function formatAMPM() {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
return strTime = date.getMonth() + '/' + date.getDay()+'/'+date.getFullYear()+' '+ hours + ':' + minutes +':'+ seconds + " " +ampm;
}
function display_c(){
var refresh = 1000; // Refresh rate in milli seconds
mytime = setTimeout('display_ct()', refresh)
}
function display_ct() {
var strcount
var currentdate = new Date();
document.getElementById('ct').innerHTML = currentdate.toDateString() + " " + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds();
tt = display_c();
}
id = 'ct' // Replace in Your id
onload = "display_ct();" // Type inside a Body Tag
My well intended answer is to use this tiny bit of JS: https://github.com/rhroyston/clock-js
clock.now --> 1462248501241
clock.time --> 11:08 PM
clock.weekday --> monday
clock.day --> 2
clock.month --> may
clock.year --> 2016
clock.since(1462245888784) --> 44 minutes
clock.until(1462255888784) --> 2 hours
clock.what.time(1462245888784) --> 10:24 PM
clock.what.weekday(1461968554458) --> friday
clock.what.day('14622458887 84') --> 2
clock.what.month(1461968554458) --> april
clock.what.year('1461968554458') --> 2016
clock.what.time() --> 11:11 PM
clock.what.weekday('14619685abcd') --> clock.js error : expected unix timestamp as argument
clock.unit.seconds --> 1000
clock.unit.minutes --> 60000
clock.unit.hours --> 3600000
clock.unit.days --> 86400000
clock.unit.weeks --> 604800000
clock.unit.months --> 2628002880
clock.unit.years --> 31536000000
Its simple and superb
$(document).ready(function () {
var fpsOut = document.getElementById('myTime');
setInterval(function () {
var d = new Date();
fpsOut.innerHTML = d;
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myTime"></div>
please find the below fiddler for the example
http://jsfiddle.net/4zVxp/483/
Here is my work around clock full format with day, date, year and time
and make Sure the date of your PC is set to the right date and if you are using PHP make sure in php.ini date.timezone= xx where xx your current timezone
function startTime()
{
var today=new Date();
// 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
var suffixes = ['','st','nd','rd','th','th','th','th','th','th','th','th','th','th','th','th','th','th','th','th','th','st','nd','rd','th','th','th','th','th','th','th','st','nd','rd'];
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var month = new Array(12);
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
document.getElementById('txt').innerHTML=(weekday[today.getDay()] + ',' + " " + today.getDate()+'<sup>'+suffixes[today.getDate()]+'</sup>' + ' of' + " " + month[today.getMonth()] + " " + today.getFullYear() + ' Time Now ' + today.toLocaleTimeString());
t=setTimeout(function(){startTime()},500);
}
<style>
sup {
vertical-align: super;
font-size: smaller;
}
</style>
<html>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
This example of UK Time Zone.. set offset for specific Time Zone.
Example : for India : +05:30 , UK : +1
function realUKTime() {
// create Date object for current location
var d = new Date();
offset ='+1';
// convert to msec
// subtract local time zone offset
// get UTC time in msec
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
// return time as a string
var s = nd.getSeconds();
var i = nd.getMinutes();
var h = nd.getHours();
var cDate = nd.getDate();
var m = nd.getUTCMonth();
var y = nd.getFullYear();
var newUkTime = nd.toDateString() + " "+ (Number(h)-1)+":"+i+':'+s
$("#realTime").html(newUkTime);
}
setInterval(realUKTime(),1000);
Output :: Mon Dec 27 2021 12:6:3
we can use :
new Date().toLocaleDateString() to fetch current date and
new Date().toLocaleTimeString() to fetch current time
Ex:
const date = new Date().toLocaleDateString();
const time = new Date().toLocaleTimeString();

Ajax get Date in dd/mm/yyyy format

var d = new Date();
var today_date = d.getDate() + '/' + month_name[d.getMonth()] + '/' + d.getFullYear();
This is how I am getting a date. It works with a slight problem. For todays date 7th of June 2011 it returns 7/11/2011, what i want it to return is 07/11/2011?
Anyone know how?
Well, you could simply check the length of d.getDate()and if it's 1 then you add a zero at the beginning. But you would like to take a look at format() to format your dates?
Like so:
("0"+1).slice(-2); // returns 01
("0"+10).slice(-2); // returns 10
Complete example:
var d = new Date(2011,1,1); // 1-Feb-2011
var today_date =
("0" + d.getDate()).slice(-2) + "/" +
("0" + (d.getMonth() + 1)).slice(-2) + "/" +
d.getFullYear();
// 01/02/2011
Try this (http://blog.stevenlevithan.com/archives/date-time-format):
var d = new Date();
d.format("dd/mm/yyyy");
Try this, this is more understandable.:
var currentTime = new Date();
var day = currentTime.getDate();
var month = currentTime.getMonth() + 1;
var year = currentTime.getFullYear();
if (day < 10){
day = "0" + day;
}
if (month < 10){
month = "0" + month;
}
var today_date = day + "/" + month + "/" + year;
document.write(today_date.toString());
And result is :
07/05/2011

Categories

Resources