I have written below method for this but it will fail when the current date will be 31.
I need to check if date is 31 it should return me 1st date of next month. Any help would be appreciated
getFutureDateTime: function () {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate() + 1;// to get current date remove "+1"
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;
},
It looks like you're trying to get the next day as a string. Your best bet is to let the Date object do the rollover between months and years for you, like this:
getFutureDateTime: function () {
var dt = new Date();
dt.setDate(dt.getDate() + 1); // Will handle rollover for you
var year = dt.getFullYear();
var month = dt.getMonth() + 1;
var day = dt.getDate();
var hour = dt.getHours();
var minute = dt.getMinutes();
var second = dt.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;
},
Note that if you're doing this in any vaguely modern environment, you can use padStart on the string (and padStart is easily polyfilled):
getFutureDateTime: function () {
var dt = new Date();
dt.setDate(dt.getDate() + 1); // Will handle rollover for you
var dateTime =
year.toString().padStart(2, "0") +
"/" +
month.toString().padStart(2, "0") +
"/" +
day.toString().padStart(2, "0") +
" " +
hour.toString().padStart(2, "0") +
":" +
minute.toString().padStart(2, "0") +
":" +
second.toString().padStart(2, "0");
return dateTime;
},
You could give yourself a utility function for the padding, to avoid repeating yourself:
function padZero2(val) {
return String(val).padStart(2, "0");
}
// ...
getFutureDateTime: function () {
var dt = new Date();
dt.setDate(dt.getDate() + 1); // Will handle rollover for you
var dateTime =
padZero2(year) +
"/" +
padZero2(month) +
"/" +
padZero2(day) +
" " +
padZero2(hour) +
":" +
padZero2(minute) +
":" +
padZero2(second);
return dateTime;
},
Similarly, if you use an ES2015 template literal, it may be a bit clearer:
getFutureDateTime: function () {
const dt = new Date();
dt.setDate(dt.getDate() + 1); // Will handle rollover for you
const dateTime = `${padZero2(year)}/${padZero2(month)}/${padZero2(day)} ${padZero2(hour)}:${padZero2(minute)}:${padZero2(second)}`;
return dateTime;
},
You don't need to have that complex function, look at this:
function getFutureDateTime() {
const regex = /(^[0-9-]+)(t)([^Z.]+)/i;
const date = new Date();
const isoFutureDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1).toISOString();
const matches = iso.match(regex);
return matches[1] + ' ' + matches[3];
}
m= require("moment")
console.log(m().add("months",2).format("YYYY/MM/DD HH:MM:SS"))
use momentjs why to reinvent wheel when you already have some nodejs library for that you can change months to days , years etc to add days,houts,years etc instead of month
https://momentjs.com/guides/#/warnings/add-inverted-param/
You sould probably add an if statement before adding the '0' to test if day==32 => day = 1 and month = month+1
getFutureDateTime: function () {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate() + 1;// to get current date remove "+1"
if (day==32){
day = 1;
month = month + 1;
}
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;
},
I am facing an issue in javascript dates, i want to added this lines in my GetFormattedDate function.
I try , i can't implement this logic in my function
var currentdate = new Date();
var myTime1 = currentdate.getHours() +':'+ (currentdate.getMinutes() <= 29 ? '00' : '30') ; //output 18:43
My code:
function GetFormattedDate(date) {
var month = ("0" + (date.getMonth() + 1)).slice(-2);
var day = ("0" + (date.getDate())).slice(-2);
var year = date.getFullYear();
var hour = ("0" + (date.getHours())).slice(-2);
var min = ("0" + (date.getMinutes())).slice(-2);
var seg = ("0" + (date.getSeconds())).slice(-2);
return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + seg + " " ;
}
Expected output
`2020-05-12 01:00:00` //if minutes are 0 to 29 then show current hours reset the minutes again start with 0 like 18:00:00 and seconds become 0
`2020-05-12 01:30:00 ` //if minutes are 29 to 59 then show current hours reset the minutes again start with 30 like 18:30:00 and seconds become 0
Do it when you set the min and seg variables
Replace the two lines
var min = ("0" + (date.getMinutes())).slice(-2);
var seg = ("0" + (date.getSeconds())).slice(-2);
with
var min = date.getMinutes() <= 29 ? '00' : '30';
var seg = '00';
function GetFormattedDate(date) {
var month = ("0" + (date.getMonth() + 1)).slice(-2);
var day = ("0" + (date.getDate())).slice(-2);
var year = date.getFullYear();
var hour = ("0" + (date.getHours())).slice(-2);
var min = date.getMinutes() <= 29 ? '00' : '30';
var seg = '00';
return year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + seg + " ";
}
console.log(GetFormattedDate(new Date));
You're passing a string to your function. Based on the link you provided in a comment, you need to parse a string representation of a date into an actual date object: var d = Date.parse("March 21, 2012"); Read more here: https://www.w3schools.com/jsref/jsref_parse.asp
Once you have a new Date object, set its seconds:
var d = new Date();
d.setSeconds(d.getSeconds() <= 29 ? 0 : 30);
Now you can pass d to your function:
GetFormattedDate(d);
I'm trying to add a leading 0 before a certain part of a date. For example, if it's 9:00am, I want to display 09:00 and not 9:0. I want to be able to add a leading zero, so I can insert it into MySQL coding.
The result I'm getting is
2018-05-029 019:07:016
Here is my Javascript code:
var login_date="";
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth()+1; /*months are from 0 - 11 */
month = '0' + month.toString().slice(-2);
var day = d.getDate();
day = '0' + day.toString().slice(-2);
var hour = d.getHours();
hour = '0' + hour.toString().slice(-2);
var minute = d.getMinutes();
minute = '0' + minute.toString().slice(-2);
var second = d.getSeconds();
second = '0' + second.toString().slice(-2);
login_date = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
console.log(login_date);
You can check for the variable length of characters, if is less than two, then add a 0.
Something like this:
var d = new Date();
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
var hour = d.getHours();
var minute = d.getMinutes();
var second = d.getSeconds();
if (month.toString().length < 2) month = '0' + month;
if (hour.toString().length < 2) hour = '0' + hour;
if (minute.toString().length < 2) minute = '0' + minute;
if (second.toString().length < 2) second = '0' + second;
console.log(year + '-' + month + '-' + day + " " + hour + ":" + minute + ":" + second)
You could just check if the value is smaller then 10 to add an "0" at the beginning.
example
var seconds = seconds < 10 ? '0'+seconds : seconds;
Your final string could be defined like:
var login_date = year + "-"
+ (month < 10 ? "0" + month : month) + "-"
+ (day < 10 ? "0" + day : day) + " "
+ (hour < 10 ? "0" + hour : hour) + ":"
+ (minute < 10 ? "0" + minute : minute) + ":"
+ (second < 10 ? "0" + second : second) ;
You can create a function addZero() that handles the concatenation of a 0 if necessary. Here is the code:
let addZero = (el) => ((el.toString().length == 1) ? '0' : '') + el.toString();
var login_date = "";
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth() + 1; /*months are from 0 - 11 */
var day = d.getDate();
var hour = d.getHours();
var minute = d.getMinutes();
var second = d.getSeconds();
login_date = year + "-" + addZero(month) + "-" + addZero(day) + " " + addZero(hour) + ":" + addZero(minute) + ":" + addZero(second);
document.write(login_date);
I want to know how to use the Date() function in jQuery to get the current date in a yyyy/mm/dd format.
Date() is not part of jQuery, it is one of JavaScript's features.
See the documentation on Date object.
You can do it like that:
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var output = d.getFullYear() + '/' +
(month<10 ? '0' : '') + month + '/' +
(day<10 ? '0' : '') + day;
See this jsfiddle for a proof.
The code may look like a complex one, because it must deal with months & days being represented by numbers less than 10 (meaning the strings will have one char instead of two). See this jsfiddle for comparison.
If you have jQuery UI (needed for the datepicker), this would do the trick:
$.datepicker.formatDate('yy/mm/dd', new Date());
jQuery is JavaScript. Use the Javascript Date Object.
var d = new Date();
var strDate = d.getFullYear() + "/" + (d.getMonth()+1) + "/" + d.getDate();
Using pure Javascript your can prototype your own YYYYMMDD format;
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + "/" + (mm[1]?mm:"0"+mm[0]) + "/" + (dd[1]?dd:"0"+dd[0]); // padding
};
var date = new Date();
console.log( date.yyyymmdd() ); // Assuming you have an open console
In JavaScript you can get the current date and time using the Date object;
var now = new Date();
This will get the local client machine time
Example for jquery LINK
If you are using jQuery DatePicker you can apply it on any textfield like this:
$( "#datepicker" ).datepicker({dateFormat:"yy/mm/dd"}).datepicker("setDate",new Date());
function GetTodayDate() {
var tdate = new Date();
var dd = tdate.getDate(); //yields day
var MM = tdate.getMonth(); //yields month
var yyyy = tdate.getFullYear(); //yields year
var currentDate= dd + "-" +( MM+1) + "-" + yyyy;
return currentDate;
}
Very handy function to use it, Enjoy. You do not require any javascript framework. it just works in with plain javascript.
I know I am Late But This Is All You Need
var date = (new Date()).toISOString().split('T')[0];
toISOString() use built function of javascript.
cd = (new Date()).toISOString().split('T')[0];
console.log(cd);
alert(cd);
Since the question is tagged as jQuery:
If you are also using jQuery UI you can use $.datepicker.formatDate():
$.datepicker.formatDate('yy/mm/dd', new Date());
See this demo.
Here is method top get current Day, Year or Month
new Date().getDate() // Get the day as a number (1-31)
new Date().getDay() // Get the weekday as a number (0-6)
new Date().getFullYear() // Get the four digit year (yyyy)
new Date().getHours() // Get the hour (0-23)
new Date().getMilliseconds() // Get the milliseconds (0-999)
new Date().getMinutes() // Get the minutes (0-59)
new Date().getMonth() // Get the month (0-11)
new Date().getSeconds() // Get the seconds (0-59)
new Date().getTime() // Get the time (milliseconds since January 1, 1970)
See this.
The $.now() method is a shorthand for the number returned by the expression (new Date).getTime().
Moment.js makes it quite easy:
moment().format("YYYY/MM/DD")
this object set zero, when element has only one symbol:
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
This object set actual full time, hour and date:
function getActualFullDate() {
var d = new Date();
var day = addZero(d.getDate());
var month = addZero(d.getMonth()+1);
var year = addZero(d.getFullYear());
var h = addZero(d.getHours());
var m = addZero(d.getMinutes());
var s = addZero(d.getSeconds());
return day + ". " + month + ". " + year + " (" + h + ":" + m + ")";
}
function getActualHour() {
var d = new Date();
var h = addZero(d.getHours());
var m = addZero(d.getMinutes());
var s = addZero(d.getSeconds());
return h + ":" + m + ":" + s;
}
function getActualDate() {
var d = new Date();
var day = addZero(d.getDate());
var month = addZero(d.getMonth()+1);
var year = addZero(d.getFullYear());
return day + ". " + month + ". " + year;
}
HTML:
<span id='full'>a</span>
<br>
<span id='hour'>b</span>
<br>
<span id='date'>c</span>
JQUERY VIEW:
$(document).ready(function(){
$("#full").html(getActualFullDate());
$("#hour").html(getActualHour());
$("#date").html(getActualDate());
});
EXAMPLE
//convert month to 2 digits<p>
var twoDigitMonth = ((fullDate.getMonth().length+1) === 1)? (fullDate.getMonth()+1) : '0' + (fullDate.getMonth()+1);
var currentDate = fullDate.getFullYear()+ "/" + twoDigitMonth + "/" + fullDate.getDate();
console.log(currentDate);<br>
//2011/05/19
You can achieve this with moment.js as well.
Include moment.js in your html.
<script src="moment.js"></script>
And use below code in script file to get formatted date.
moment(new Date(),"YYYY-MM-DD").utcOffset(0, true).format();
FYI - getDay() will give you the day of the week... ie: if today is Thursday, it will return the number 4 (being the 4th day of the week).
To get a proper day of the month, use getDate().
My example below... (also a string padding function to give a leading 0 on single time elements. (eg: 10:4:34 => 10:04:35)
function strpad00(s)
{
s = s + '';
if (s.length === 1) s = '0'+s;
return s;
}
var currentdate = new Date();
var datetime = currentdate.getDate()
+ "/" + strpad00((currentdate.getMonth()+1))
+ "/" + currentdate.getFullYear()
+ " # "
+ currentdate.getHours() + ":"
+ strpad00(currentdate.getMinutes()) + ":"
+ strpad00(currentdate.getSeconds());
Example output: 31/12/2013 # 10:07:49If using getDay(), the output would be 4/12/2013 # 10:07:49
This will give you current date string
var today = new Date().toISOString().split('T')[0];
Try this....
var d = new Date();
alert(d.getFullYear()+'/'+(d.getMonth()+1)+'/'+d.getDate());
getMonth() return month 0 to 11 so we would like to add 1 for accurate month
Reference by : https://www.w3schools.com/jsref/jsref_obj_date.asp
you can use this code:
var nowDate = new Date();
var nowDay = ((nowDate.getDate().toString().length) == 1) ? '0'+(nowDate.getDate()) : (nowDate.getDate());
var nowMonth = ((nowDate.getMonth().toString().length) == 1) ? '0'+(nowDate.getMonth()+1) : (nowDate.getMonth()+1);
var nowYear = nowDate.getFullYear();
var formatDate = nowDay + "." + nowMonth + "." + nowYear;
you can find a working demo here
var d = new Date();
var today = d.getFullYear() + '/' + ('0'+(d.getMonth()+1)).slice(-2) + '/' + ('0'+d.getDate()).slice(-2);
The jQuery plugin page is down. So manually:
function strpad00(s)
{
s = s + '';
if (s.length === 1) s = '0'+s;
return s;
}
var now = new Date();
var currentDate = now.getFullYear()+ "/" + strpad00(now.getMonth()+1) + "/" + strpad00(now.getDate());
console.log(currentDate );
console.log($.datepicker.formatDate('yy/mm/dd', new Date()));
Using the jQuery-ui datepicker, it has a handy date conversion routine built in so you can format dates:
var my_date_string = $.datepicker.formatDate( "yy-mm-dd", new Date() );
Simple.
This is what I came up with using only jQuery. It's just a matter of putting the pieces together.
//Gather date information from local system
var ThisMonth = new Date().getMonth() + 1;
var ThisDay = new Date().getDate();
var ThisYear = new Date().getFullYear();
var ThisDate = ThisMonth.toString() + "/" + ThisDay.toString() + "/" + ThisYear.toString();
//Gather time information from local system
var ThisHour = new Date().getHours();
var ThisMinute = new Date().getMinutes();
var ThisTime = ThisHour.toString() + ":" + ThisMinute.toString();
//Concatenate date and time for date-time stamp
var ThisDateTime = ThisDate + " " + ThisTime;
You can do this:
var now = new Date();
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM
OR Something like
var dateObj = new Date();
var month = dateObj.getUTCMonth();
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var newdate = month + "/" + day + "/" + year;
alert(newdate);
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var year = d.getYear();
var today = (day<10?'0':'')+ day + '/' +(month<10?'0':'')+ month + '/' + year;
alert(today);
I just wanted to share a timestamp prototype I made using Pierre's idea. Not enough points to comment :(
// US common date timestamp
Date.prototype.timestamp = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
var h = this.getHours().toString();
var m = this.getMinutes().toString();
var s = this.getSeconds().toString();
return (mm[1]?mm:"0"+mm[0]) + "/" + (dd[1]?dd:"0"+dd[0]) + "/" + yyyy + " - " + ((h > 12) ? h-12 : h) + ":" + m + ":" + s;
};
d = new Date();
var timestamp = d.timestamp();
// 10/12/2013 - 2:04:19
Get current Date format dd/mm/yyyy
Here is the code:
var fullDate = new Date();
var twoDigitMonth = ((fullDate.getMonth().toString().length) == 1)? '0'+(fullDate.getMonth()+1) : (fullDate.getMonth()+1);
var twoDigitDate = ((fullDate.getDate().toString().length) == 1)? '0'+(fullDate.getDate()) : (fullDate.getDate());
var currentDate = twoDigitDate + "/" + twoDigitMonth + "/" + fullDate.getFullYear();
alert(currentDate);
function createDate() {
var date = new Date(),
yr = date.getFullYear(),
month = date.getMonth()+1,
day = date.getDate(),
todayDate = yr + '-' + month + '-' + day;
console.log("Today date is :" + todayDate);
You can add an extension method to javascript.
Date.prototype.today = function () {
return ((this.getDate() < 10) ? "0" : "") + this.getDate() + "/" + (((this.getMonth() + 1) < 10) ? "0" : "") + (this.getMonth() + 1) + "/" + this.getFullYear();
}
This one-liner will give you YYYY-MM-DD:
new Date().toISOString().substr(0, 10)
'2022-06-09'
Let say date current date is 10 Jan 2011. When I get date using js code
var now = new Date();
var currentDate = now.getDate() + '-' + (now.getMonth() + 1) + '-' + now.getFullYear();
It reutrns "10-1-2011"
but I want "10-01-2011" (2 places format)
var now = new Date();
alert((now .getMonth() < 9 ? '0' : '') + (now .getMonth() + 1))
Here's a nice short way:
('0' + (now.getMonth() + 1)).slice(-2)
So:
var currentDate = now.getDate() + '-' + ('0' + (now.getMonth() + 1)).slice(-2) + '-' + now.getFullYear();
(now.getMonth() + 1) adjust the month
'0' + prepends a "0" resulting in "01" or "012" for example
.slice(-2) slice off the last 2 characters resulting in "01" or "12"
function leftPad(text, length, padding) {
padding = padding || "0";
text = text + "";
var diff = length - text.length;
if (diff > 0)
for (;diff--;) text = padding + text;
return text;
}
var now = new Date();
var currentDate = leftPad(now.getDate(), 2) + '-' + leftPad(now.getMonth() + 1, 2js) + '-' + now.getFullYear();
the quick and nasty method:
var now = new Date();
var month = now.getMonth() + 1;
var currentDate = now.getDate() + '-' + (month < 10 ? '0' + month : month) + '-' + now.getFullYear();
var now = new Date();
now.format("dd-mm-yyyy");
would give 10-01-2011