using date in javascript - javascript

I have trouble using date in Javascript, in PHP you use something like date("Y-m-d H:i s") to retrieve the specific date and time, how can I achieve this in Javascript? the getMonth() method only returns 1 digit, I really need them to be in 2 digits

Since I made comments on almost all answers, I'd better post my suggestion
DEMO
function pad(num) { return ("0"+num).slice(-2); }
function getDisplayDate() {
var date = new Date();
return date.getFullYear()+
"-"+pad(date.getMonth()+1)+
"-"+pad(date.getDate())+
" "+pad(date.getHours())+
":"+pad(date.getMinutes())+
":"+pad(date.getSeconds());
}
setInterval(function() {
document.getElementById("time").innerHTML=getDisplayDate();
},500);

why dont you add 0 before when you get <10

Try this :
function dateToYMD(date) {
var d = date.getDate();
var m = date.getMonth() + 1;
var y = date.getFullYear();
return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d) + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
}
var d = new Date();
alert(dateToYMD(d));

This code is adjusted based on the pointers given by #mplungjan -- (credits to him please)
Also check out his solution, which is a better one for use with date digits.
var str = 10; // month-digit from getMonth()
function pad(val) {
return "0" + val;
}
var month = str < 10 ? pad(str) : str;
console.log(month);

you can year, minutes, etc from Date class. You can get 2 digits month using some trick like example below. e.g
Date.prototype.getLongMonth = function() {
var month = this.getMonth();
if (String(month).length == 1) month = '0'.concat(month);
return month;
}
var now = new Date();
var theDate = now.getFullYear() + '-' + now.getLongMonth() + '-' + now.getDate() + ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
console.log(theDate); // result : 2013-02-17 12:41:2

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 + '';

Get timestamp in jquery in a particular format without a plugin

I want to get time stamp as follows in jquery 20140410091906. That is in the format YYYYMMDDHHMMSS.How can i do this without using any plugin.
You can do this:
new Date().toISOString().replace(/\D/g,"").substr(0,14);
toISOString() returns the date in year-month-dayThour:minutes:seconds.millisecondsZ format.
So I just removed the TZ-:. from the string and removed the milliseconds.
You can make your own format, for example:
var myDate = new Date();
So if you want to display it as mm/dd/yyyy, you would do this:
var displayDate = (myDate.getMonth()+1) + '/' + (myDate.getDate()) + '/' + myDate.getFullYear();
Try something like
function lpad(str, len, char) {
str += '';
if (str.length >= len) {
return str;
}
return new Array(len - str.length + 1).join(char) + str;
}
function getTs() {
var date = new Date();
var str = date.getFullYear() + lpad(date.getMonth(), 2, 0) + lpad(date.getDate(), 2, 0) + lpad(date.getHours(), 2, 0) + lpad(date.getMinutes(), 2, 0) + lpad(date.getSeconds(), 2, 0);
return str;
}
console.log(getTs())
Demo: Fiddle
This will do,
var d= new Date
d.toISOString().replace(/\D+/g,'').substr(0, 14)
Fiddle Demo
Date.prototype.YYYYMMDDHHMMSS = function () {
var yyyy = this.getFullYear().toString(),
mm = (this.getMonth() + 1).toString(),
dd = this.getDate().toString(),
hh = this.getHours().toString(),
min = this.getMinutes().toString(),
ss = this.getSeconds().toString();
return yyyy + (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]);
};
var d = new Date();
console.log(d.YYYYMMDDHHMMSS());

Show current date

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;

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

How to get correct gmt time in Javascript

For using the Amazon mechanical turk API I want to get the current GMT time and show it in ISO format
2011-02-24T20:38:34Z
I am wondering if there is any way to correctly get the gmt time and also be able to reformat it with ISO format. I can use something like now.toGMTString(); but it makes a string out of the date and it is hard to reformat it with ISO.
var year = now.getUTCFullYear()
var month = now.getUTCMonth()
var day= now.getUTCDay()
var hour= now.getUTCHours()
var mins= now.getUTCMinutes()
var secs= now.getUTCSeconds()
var dateString = year + "-" + month + "-" + day + "T" + hour + ":" + mins + ":" + secs + "Z"
You should be using UTC now instead of GMT. (Amounts to almost the same thing now, and it is the new standard anyway)
I believe this will work for you:
Number.prototype.pad = function(width,chr){
chr = chr || '0';
var result = this;
for (var a = 0; a < width; a++)
result = chr + result;
return result.slice(-width);
}
Date.prototype.toISOString = function(){
return this.getUTCFullYear().pad(4) + '-'
+ this.getUTCMonth().pad(2) + '-'
+ this.getUTCDay().pad(2) + 'T'
+ this.getUTCHours().pad(2) + ':'
+ this.getUTCMinutes().pad(2) + ':'
+ this.getUTCSeconds().pad(2) + 'Z';
}
Usage:
var d = new Date;
alert('ISO Format: '+d.toISOString());
Not much more different than every else's answer, but make it built-in to the date object for convenience
function pad(num) {
return ("0" + num).slice(-2);
}
function formatDate(d) {
return [d.getUTCFullYear(),
pad(d.getUTCMonth() + 1),
pad(d.getUTCDate())].join("-") + "T" +
[pad(d.getUTCHours()),
pad(d.getUTCMinutes()),
pad(d.getUTCSeconds())].join(":") + "Z";
}
formatDate(new Date());
Output:
"2011-02-24T21:01:55Z"
This script can take care of it
/* use a function for the exact format desired... */
function ISODateString(d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'}
var d = new Date();
document.write(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z

Categories

Resources