How to add a day (or 2 days) to date 31.07.2012 and return result in format dd.MM.yyyy (same format as input date)?
The best way would be to use the javascript date object. The date object in javascirpt is initialized as mm/dd/yyyy or as Date(year,month-1, date). That is,
dateString = "31.07.2012"
dateSplit = dateString.split('.')
date = new Date(dateSplit[2], dateSplit[1]-1, dateSplit[0])
date.setDate(date.getDate()+2)
newDateString = ((date.getDate() > 10) ? date.getDate() : ("0" + date.getDate())) + "." + ((date.getMonth()+1 > 10) ? date.getMonth()+1 : ("0" + (date.getMonth()+1))) + "." + (date.getFullYear())
month-1 is used in Date(year,month-1, date) because months start with 0
The result will be
"02.08.2012"
var numDaysToAdd = 2;
var inputDateString = "31.07.2012";
var resultDate = stringToDate(inputDateString);
resultDate.setDate( resultDate.getDate()+numDaysToAdd );
var result = dateToString( resultDate );
alert(result);
function stringToDate( aString )
{
var dateArray = aString.split(".");
return new Date(dateArray[2],dateArray[1]-1,dateArray[0]);
}
function dateToString( aDate )
{
var date = aDate.getDate();
date = (date > 9) ? date : "0"+date.toString();
var month = aDate.getMonth()+1;
month = (month > 9) ? month : "0"+month.toString();
var year = aDate.getFullYear();
return (date+"."+month+"."+year);
}
/**
* Format date (2012.08.31)
*/
Date.prototype.format = 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
}
/**
* Increase current time
*/
Date.prototype.increase_days = function(days) {
this.setTime(this.getTime() + (days * (1000 * 60 * 60 * 24)));
return this;
}
//usage:
var date = new Date();
date.increase_days(2);
console.log(date.format());
assuming inputDateString format is dd.mm.yyyy
function addDaysToDate (inputDateString ,noOfDays ){
var myDate=dateString.split(".");
var newDate=myDate[1]+"/"+myDate[0]+"/"+myDate[2];
var dateInMilliSec = new Date(newDate).getTime();
var addDaysToTime = new Date(dateInMilliSec + (86400000 * noOfDays));
var dd = addDaysToTime.getDate();
var MM = addDaysToTime.getMonth()+1;
var yyyy = addDaysToTime.getFullYear();
return dd+"."+MM+"."+yyyy;
};
This will do it for you
var d = "31.07.2012";
d = d.split(".");
date = new Date(d[2],d[1]-1,d[0]);
date.setDate(date.getDate() + 2);
document.body.innerHTML += (date.getDate() + "." + date.getMonth() + "." + (date.getFullYear()));
Related
So what I have is a time string which shows the time as h:m:s.ms
But the problem is that I want to covert them to timestamp values it shows NaN values.
I am using Date.parse() to convert the time into timestamp.
Here is the code that I have tried.
var date;
function myFunction() {
var d = new Date();
var h = addZero(d.getHours(), 2);
var m = addZero(d.getMinutes(), 2);
var s = addZero(d.getSeconds(), 2);
var ms = addZero(d.getMilliseconds(), 3);
var maindate = h + ":" + m + ":" + s + "." + ms ;
var datestring = Date.parse(maindate)
var data = Math.random(0,1);
console.log("Date : ", maindate) ;
console.log("Data : ", data);
}
myFunction();
You can see the date and data in the console window.
the date variable here shows NaN Value.
Please tell me what I am doing wrong.
If you want a timestamp you need a full time with day, month and year
var date;
function myFunction() {
var d = new Date();
var h = addZero(d.getHours(), 2);
var m = addZero(d.getMinutes(), 2);
var s = addZero(d.getSeconds(), 2);
var ms = addZero(d.getMilliseconds(), 3);
var day = d.getDate();
var month = d.getMonth() + 1; // getMonth returns an integer between 0 and 11
var year = d.getFullYear();
var maindate = `${day}-${month}-${year} ${h}:${m}:${s}.${ms}`;
var datestring = Date.parse(maindate)
console.log("Data : ", datestring);
}
myFunction();
Parsing dates is a pain in JavaScript as there's no extensive native support. However you could do something like the following by relying on the Date(year, month, day [, hour, minute, second, millisecond]) constructor signature of the Date object.
var dateString = '17-09-2013 10:08',
dateTimeParts = dateString.split(' '),
timeParts = dateTimeParts[1].split(':'),
dateParts = dateTimeParts[0].split('-'),
date;
date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]);
console.log(date.getTime()); //1379426880000
console.log(date); //Tue Sep 17 2013 10:08:00 GMT-0400
You could also use a regular expression with capturing groups to parse the date string in one line.
var dateParts = '17-09-2013 10:08'.match(/(\d+)-(\d+)-(\d+) (\d+):(\d+)/);
console.log(dateParts); // ["17-09-2013 10:08", "17", "09", "2013", "10", "08"]
As I want to get the timestamp in result. I got my sholution of the above question that I posted
Here is the Final code which is giving me the expected result.
function addZero(x,n) {
while (x.toString().length < n) {
x = "0" + x;
}
return x;
}
var date;
function myFunction() {
var d = new Date();
var day = d.getDate();
var month = d.getMonth() + 1; // Since getMonth() returns month from 0-11 not 1-12
var year = d.getFullYear();
var h = addZero(d.getHours(), 2);
var m = addZero(d.getMinutes(), 2);
var s = addZero(d.getSeconds(), 2);
var ms = addZero(d.getMilliseconds(), 3);
var maindate = year +"-" + day + "-" + month +" "+ h + ":" + m + ":" + s + "." + ms ;
var datestring = Date.parse(maindate)
var data = Math.random(0,1);
console.log("Date : ", datestring) ;
console.log("Data : ", data);
}
myFunction();
I had to include the day month and year value also. WHich I updated in the Answer. rest of the code works fine.
For this, you don't need your addZero() function any more and it's unnecessary to delacre var date; globally.
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var ms = d.getMilliseconds();
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
var maindate = day + '-' + month + '-' + year + ' ' + h + ':' + m + ':' + s + '.' + ms;
var datestring = Date.parse(maindate);
console.log("Data : ", datestring);
Take a look at momentjs.com, maybe this could be a clean and simple solution for you too - depending on your environment.
I have a formatted date as a string '021519' using javascript which return NAN on display in html.
Note I have a xslt using the javascript.
var newDate = '';
var formatedDate = new Date(date);
var year = formatedDate.getFullYear().toString();
var month = (1 + formatedDate.getMonth()).toString();
if(parseInt(month) < 10)
{
month = "0" + month;
}
var day = formatedDate.getDate().toString();
if(dateFormat == '1')
{
newDate = month + day + year.substr(2,4);
}
else
{
newDate = month + day + year;
}
var newLeftStart3 = parseInt(startPosition) - 1;
var newLeftEnd3 = newLeftStart + newDate.length;
var newRightStart3 = parseInt(endPosition) - newDate.length;
var newRightEnd3 = newRightStart + newDate.length;
if(alignment == '1')
{
addendaSpace = addendaSpace.substr(0, newLeftStart3) + newDate + addendaSpace.substr(newLeftEnd3);
}
if(alignment == '2')
{
addendaSpace = addendaSpace.substr(0, newRightStart3) + newDate + addendaSpace.substr(newRightEnd3);
}
newDate is displaying as NaN i hope this code helps.
I usually format dates in javascript this way:
var d = new Date();
var date = d.getDate();
var month = d.getMonth() + 1; //Months are zero based
var year = d.getFullYear();
console.log(date + "-" + month + "-" + year);
I am trying to find the difference between two dates,when the user wants to change arrival date, remember the number of days between arrival/departure before the change , after changing arrival date , automatically set departure date to be x days after arrival date ,
So, if i have 01JUN17 - 05JUN17 (4days) and the user changes the arrival date to 04JUN17 then set departure to 08JUN17 (+4 days)
function changedDate() {
var startDate = $("#Arrival").val().split("-");
var endDate = $("#Departure").val().split("-");
var arrivalDate = new Date(startDate[2], startDate[1] - 1, startDate[0]);
var departureDate = new Date(endDate[2], endDate[1] - 1, endDate[0]);
var timeDiff = Math.abs(departureDate.getDate() - arrivalDate.getDate());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
if (arrivalDate >= departureDate) {
var arrDate = arrivalDate;
arrDate.setDate(arrDate.getDate() + 1);
var month = arrDate.getMonth() + 1;
if (month < 10)
month = '0' + month;
var day = arrDate.getDate();
if (day < 10)
day = '0' + day;
var year = arrDate.getFullYear();
$("#Departure").val(day + '-' + month + '-' + year);
}
if (timeDiff > 1) {
var arrDate = arrivalDate;
var depDate = departureDate;
arrDate.setDate(arrDate.getDate());
depDate.setDate(depDate.getDate() + diffDays);
var month = arrDate.getMonth() + 1;
if (month < 10)
month = '0' + month;
var day = arrDate.getDate();
if (day < 10)
day = '0' + day;
var year = arrDate.getFullYear();
var monthd = depDate.getMonth() + 1;
if (monthd < 10)
monthd = '0' + month;
var dayd = depDate.getDate();
if (dayd < 10)
dayd = '0' + day;
var yeard = depDate.getFullYear();
$("#Arrival").val(day + '-' + month + '-' + year);
$("#Departure").val(dayd + '-' + monthd + '-' + yeard);
}
if(arrivalDate < departureDate) {
var arrDate = arrivalDate;
arrDate.setDate(arrDate.getDate() + 1);
var month = arrDate.getMonth() + 1;
if (month < 10)
month = '0' + month;
var day = arrDate.getDate();
if (day < 10)
day = '0' + day;
var year = arrDate.getFullYear();
$("#Departure").val(day + '-' + month + '-' + year);
}
}
this condition not related with the validation that i want this is to
set departureDate +1 after arrival date on change
if (arrivalDate >= departureDate)
this condition not related with the validation that i want this is to
set departureDate +1 after arrival date on change
if(arrivalDate < departureDate)
this condition i make it for this validation but didn't work
if (timeDiff > 1)
Instead of using the getDate() method to calculate the timeDiff, use getTime() and do a simple subtraction, followed by a millisecond-to-days refactoring.
Something like this:
var startDate = $("#Arrival").val().split("-");
var endDate = $("#Departure").val().split("-");
var arrivalDate = new Date(startDate[2], startDate[1] - 1, startDate[0]);
var departureDate = new Date(endDate[2], endDate[1] - 1, endDate[0]);
var timeDiff = Math.abs(departureDate.getTime() - arrivalDate.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
Additionally, while subtracting Date type values, the getTime() method becomes optional and a direct subtraction departureDate - arrivalDate can also be done.
If you're using datejs, creating a TimeSpan will help here.
var sync = function () {
var val1 = $("#Arrival").val();
var val2 = $("#Departure").val();
var startDate = Date.parseExact(val1, "ddMMMyy");
var endDate = Date.parseExact(val2, "ddMMMyy");
var diff = new TimeSpan(endDate - startDate);
var newEndDate = startDate.add(diff.days).days();
$("#Departure").val(newEndDate.toString("ddMMyyy"));
};
You could trigger this function to automatically fire by wiring up a change listener on the startDate input field. Just a thought.
Hope this helps.
To do this you need to remember either the arrival date before it was modified, or the number of days between arrival and departure dates. That way you can adjust the departure date by whatever amount the arrival date moved by.
You can store the "old" arrival date in lots of places, the defaultValue might be a good place. So when arrival date is updated, compare the new arrival date to the old one, set the old do the new one and adjust the departure date accordingly, e.g.
// Some helper functions
function parseDMY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[1], b[0]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
function formatDate(date) {
if (isNaN(date)) return date.toString();
function z(n){return (n<10?'0':'')+n}
return z(date.getDate()) + '-' +
z(date.getMonth()+1) + '-' +
date.getFullYear();
}
function arrivalChange() {
// Check value entered is valid, if so,
// make sure formatted correctly
var arrDate = parseDMY(this.value);
// Deal with invalid input
if (isNaN(arrDate)) {
this.value = "Invalid date";
this.focus();
return;
}
// Tidy formatting
this.value = formatDate(arrDate);
var daysDiff, depDate;
var depEl = this.form.departureDate;
// Get number of days shifted and move departure date accordingly
daysDiff = Math.round((arrDate - parseDMY(this.defaultValue)) / 8.64e7);
this.defaultValue = this.value;
depDate = parseDMY(this.form.departureDate.defaultValue);
depDate.setDate(depDate.getDate() + daysDiff);
this.form.departureDate.value = formatDate(depDate);
this.form.departureDate.defaultValue = formatDate(depDate);
}
function departureChange(){
// Check value entered is valid, if so,
// make sure formatted correctly
var depDate = parseDMY(this.value);
if (isNaN(depDate)) {
this.value = 'Invalid date';
this.focus();
} else {
this.value = formatDate(depDate);
this.defaultValue = formatDate(depDate);
}
}
// Set dates in inputs, attach listeners
window.onload = function() {
var form = document.forms[0];
var now = new Date();
form.arrivalDate.value = formatDate(now);
form.arrivalDate.defaultValue = form.arrivalDate.value;
now.setDate(now.getDate() + 1);
form.departureDate.value = formatDate(now);
form.departureDate.defaultValue = form.departureDate.value;
form.arrivalDate.addEventListener('change', arrivalChange, false);
form.departureDate.addEventListener('change', departureChange, false);
};
<form onsubmit="return false;">
Arrival date (dd-mm-yyy): <input name="arrivalDate"><br>
Departure date (dd-mm-yyy): <input name="departureDate"><br>
<input type="reset">
</form>
If the user enters an invalid date at any time, pressing reset should get back the previous values.
I want to get all dates in between 2 dates. So here I have mentioned statdate is date and end date is weekdate. In between 2 dates I want all dates.
Actully I am getting all dates But Not proper Format ,what i want in this format DD/MM/YY.
Now I am Getting in default Format (Sat Jun 09 2007 17:46:21)
$(document).ready(function () {
$("#day").click(function () {
startJsonSession();
return false;
});
function startJsonSession() {
var inputdate = $('#inputdate').val();
//alert("Input Date!!!" + inputdate );
var d = new Date(inputdate);
var nowMS = d.getTime(); // get # milliseconds for today
//alert(nowMS);
var week = 1000 * 60 * 60 * 24 * 7; // milliseconds in one week
//alert(week);
var oneWeekFromNow = new Date(nowMS + week);
//alert("oneWeekFromNow!!!" + oneWeekFromNow);
var fromdate = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if (fromdate < 10) {
fromdate = "0" + fromdate;
}
if (month < 10) {
month = "0" + month;
}
//var date = fromdate + "/" + month + "/" + year;
var date = year + "/" + month + "/" + fromdate;
alert("InputDate!!!!" + date);
//var weekdate=oneWeekFromNow.getDate() + "/" + month + "/" + year;
var weekdate = year + "/" + month + "/" + oneWeekFromNow.getDate();
alert("weekdate!!!" + weekdate);
var tomorrow = new Date(d.getTime() + (24 * 60 * 60 * 1000));
var tomorrowdate = tomorrow.getDate();
var month1 = tomorrow.getMonth() + 1;
var year1 = tomorrow.getFullYear();
if (tomorrowdate < 10) {
tomorrowdate = "0" + tomorrowdate;
}
if (month1 < 10) {
month1 = "0" + month1;
}
//var nextday = tomorrowdate + "/" + month1 + "/" + year1;
var nextday = year1 + "/" + month1 + "/" + tomorrowdate;
alert("tomorrow!!!!" + nextday);
var d1 = new Date(date);
alert("D1!!!!!" + d1.);
var d2 = new Date(weekdate);
var aDates = [];
do {
aDates.push(d1.toString());
d1.setDate(d1.getDate() + 1);
}
while (d1 <= d2);
alert("Dates!!!" + aDates);
//alert(aDates.join("\n"));
}
});
You can do it in this way
$("#getDate").click(function () {
var start = $("#startdate").datepicker("getDate"),
end = $("#enddate").datepicker("getDate");
currentDate = new Date(start),
between = [];
while (currentDate < end) {
between.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
for (var i = 0; i < between.length; i++) {
var date = $.datepicker.formatDate('dd/mm/yy', new Date(between[i]));
between[i] = date;
}
console.log(between)
})
Here 'between' is the array which contains all your required Date
SEE DEMO HERE
alert("Dates!!!" + aDates.getDate()+"/"+ (aDates.getMonth()+1)+"/"+ aDates.getFullYear());
You seem to want to get a array of date strings in d/m/y format given an input string in the same format. The following functions will do that.
// Parse a string in dmy format
// return a date object, NaN or undefined
function parseDMY(s) {
var b = s.match(/\d+/g);
if (b) {
return new Date(b[2], --b[1], b[0]);
}
}
// Given a date object, return a string in dd/mm/yyyy format
function formatDMY(date) {
function z(n){return (n<10? '0' : '') + n;}
return z(date.getDate()) + '/' + z(date.getMonth() + 1) + '/' + date.getFullYear();
}
function getWeekDates(s) {
var d = parseDMY(s);
var dates = [];
if (d) {
for (var i=0; i<7; i++) {
dates.push(formatDMY(d));
d.setDate(d.getDate() + 1);
}
return dates;
}
}
console.log(getWeekDates('7/7/2014').join());
// 07/07/2014,08/07/2014,09/07/2014,10/07/2014,11/07/2014,12/07/2014,13/07/2014
Note that adding 1 day to a date is preferred over adding milliseconds as it allows the Date object to take account of daylight saving changes that might be involved.
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'