How to calculate date and change the format of the date - javascript

How to calculate the date and change the date format.
I can't compare the date code below. I want to know why? I want an example to compare date or calculate day results of different days
I want to change format before and after that comparing date (formatDate: dd/mm/yyyy)
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();
var d1 = curr_date + "/" + curr_month + "/" + curr_year;
//alert(d1); change format date completed 12/04/2019
var date2 = new Date("04/12/2018");
var curr_date2 = date2.getDate();
var curr_month2 = date2.getMonth() + 1;
var curr_year2 = date2.getFullYear();
var d2 = curr_date2 + "/" + curr_month2 + "/" + curr_year2;
//alert(d2); // change format date completed 12/04/2018
if (d1 > d2) {
console.log("aaa");
} else {
console.log("bbb");
}

There are no issues with the first part of your code when you are converting them from JavaScript Date objects to the mentioned date formats.
However, when it comes to comparing the dates, you should use getTime() on the Date objects.
if(d.getTime() > date2.getTime()) {
console.log("aaa");
}else{
console.log("bbb");
}
What you tried to do on your code is to compare d1 and d2, which is wrong because they are both strings, and will likely give you the wrong solution.
Here is the full code. Basically, you only need to change the last chunk of your code with that if.. else statement.
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();
var d1 = curr_date + "/" + curr_month + "/" + curr_year;
console.log(d1);
//alert(d1); change format date completed 12/04/2019
var date2 = new Date("04/12/2018");
var curr_date2 = date2.getDate();
var curr_month2 = date2.getMonth() + 1;
var curr_year2 = date2.getFullYear();
var d2 = curr_date2 + "/" + curr_month2 + "/" + curr_year2;
console.log(d2);
//alert(d2); // change format date completed 12/04/2018
console.log(d.getTime())
console.log(date2.getTime())
// only change the below
if(d.getTime() > date2.getTime()) {
console.log("aaa");
} else {
console.log("bbb");
}

Related

JavaScript is returning NAN for a string '021519' on html

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);

Formatting and Calculating dates with javascript

I'm new to javascript and I'm trying to generate a date that is:
A.) Formatted (mm/dd/yyyy)
B.) Displayed as three months later than the actual date.
I've spliced together a few things I could find and is seems to work to return the correct date, but I'm concerned it will break later in the year. Is there a better way to accomplish what I'm trying to do? The script is below, thanks in advance for the help.
<script type="text/javascript">
var dt = new Date();
var month = dt.getMonth();
var day = dt.getDate();
var year = dt.getFullYear();
if (month == 9) { var dt = new Date();
var month = dt.getMonth()-8;
var day = dt.getDate();
var year = dt.getFullYear();
var next_year = dt.getFullYear()+1;
document.write(month + '-' + day + '-' + next_year)}
else if (month == 10) { var dt = new Date();
var month = dt.getMonth()-8;
var day = dt.getDate();
var year = dt.getFullYear();
var next_year = dt.getFullYear()+1;
document.write(month + '-' + day + '-' + next_year)}
else if (month == 11) { var dt = new Date();
var month = dt.getMonth()-8;
var day = dt.getDate();
var year = dt.getFullYear();
var next_year = dt.getFullYear()+1;
document.write(month + '-' + day + '-' + next_year)}
else { var dt = new Date();
var month = dt.getMonth()+4;
var day = dt.getDate();
var year = dt.getFullYear();
document.write(month + '-' + day + '-' + year);}
</script>
The date object has methods that allows not only to set month, date and year, but get too.
function getMyDate() {
var date = new Date();
date.setMonth(date.getMonth() + 3);
return (date.getMonth() + 1) + '-' + date.getDate() + '-' + date.getFullYear();
}
document.write(getMyDate());
P.S. The scope of var is the function, not block {}. So, if you declared var dt at the top of your scope, you mustn’t use var dt in if statement. It’s a mistake.
You don't need to worry about dealing with the last three months of the year. Adding three months to a a date that causes it to 'overflow' will correctly set it to next year (eg adding three months to November 2015 will produce a date in February 2016).
var dt = new Date();
dt.setMonth(dt.getMonth() + 3);
document.write((dt.getMonth() + 1) + "-" + dt.getDate() + "-" + dt.getFullYear();
For what it's worth, your code looks correct. Just unnecessarily complex.
To print todays date you should concat the date values:
var d = new Date();
var str = (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();
if you want to add months to your date:
var d = new Date();
var threeMonthsFromToday = new Date(new Date(d).setMonth(d.getMonth()+3));
var str = (d.getMonth() + 1) + '/' + d.getDate() + '/' + d.getFullYear();

Date to String object conversion

I have use the following code snippet to convert the Date object to string .
var startDate = new Date();
var result = Globalize.parseDate(startDate, "MM/DD/YYYY");
but it will return the null value. How to convert the Date object to string specific format ?
To know all possible ways, check this link out.
I've put all the DEMOS here...
STANDARD JS:
<script type="text/javascript">
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months start with zero
var curr_year = d.getFullYear();
document.write(curr_month + "/" + curr_date + "/" + curr_year);
</script>
MOMENT.JS:
Download here...
<script>
var a = moment([2010, 1, 14, 15, 25, 50, 125]);
a.format("MM/DD/YYYY,");
</script>
Don't want to download, simply add this line:
<script src="http://momentjs.com/downloads/moment.min.js"></script>
jQuery UI:
$.datepicker.formatDate('yy-mm-dd', new Date(2007, 1 - 1, 26));
IE:
var d1=new Date();
d1.toString('MM-dd-yyyy');
Globalize:
var startDate = new Date();
var result = Globalize.format(startDate, "MM/DD/YYYY");
I assume that you are using Globalize.
What you should do is to format the date, not parse it.
var startDate = new Date();
var result = Globalize.format(startDate, "MM/DD/YYYY");
You can simply use
var startDate = new Date();
alert((startDate .getMonth() + 1) + '/' + startDate .getDate() + '/' + startDate .getFullYear());
DEMO
Try this:
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
document.write(curr_date + "-" + curr_month + "-" + curr_year);
Reference: Where can I find documentation on formatting a date in JavaScript?
MomentJS has a very robust set of time formatting options, you can use them.
Below is the example how it will work in your case
moment(stateDate).format("MM/DD/YYYY");
This function takes a date object as a parameter and returns a string in MM/DD/YYYY format :
function format(date) {
return [
('0' + (date.getMonth() + 1)).slice(-2),
('0' + date.getDate()).slice(-2),
date.getFullYear()
].join('/')
}
Usage example (gives today's date in MM/DD/YYYY format) :
format(new Date) // "01/03/2014"
You can easily change the resulting format with a few modifications :
function format(date) {
return [
date.getDate(),
date.getMonth() + 1,
('' + date.getFullYear()).slice(-2)
].join('-')
}
Usage example (gives today's date in D-M-YY format) :
format(new Date) // "3-1-14"
Playing around
I've tuned the function a bit, this might be interesting for very basic needs :)
function format(date, format) {
var i = 0, bit;
if (!format) format = 'MM/DD/YYYY'; // default
format = format.split(/([^DMY]+)/i);
while (bit = format[i]) {
switch (bit.charAt(0).toUpperCase()) {
case 'D': format[i] = date.getDate(); break;
case 'M': format[i] = date.getMonth() + 1; break;
case 'Y': format[i] = date.getFullYear(); break;
}
if (bit.length === 2) {
format[i] = ('0' + format[i]).slice(-2);
}
i += 2;
}
return format.join('');
}
Usage examples :
format(new Date) // "01/03/2014" (default)
format(new Date, 'd/m/y') // "3/1/2014"
format(new Date, 'D/M/Y') // "3/1/2014"
format(new Date, 'DD-MM-YY') // "03-01-14"
format(new Date, 'M/YY') // "1/14"

In Javascript how can i get todays date in this format yyyymmdd

Like i need to get todays date in format like 20120924 (yyyymmdd).How can i get this in javascript.
You could add a method to the date prototype, so you can use it on any date object:
Date.prototype.toMyString = function () {
function padZero(obj) {
obj = obj + '';
if (obj.length == 1)
obj = "0" + obj
return obj;
}
var output = "";
output += this.getFullYear();
output += padZero(this.getMonth()+1);
output += padZero(this.getDate());
return output;
}
var d = new Date();
alert(d.toMyString()); // Today
var otherDate = new Date(2012,0,1);
alert(otherDate.toMyString());​ //Jan 1 2012
Fiddle: http://jsfiddle.net/johnkoer/4rk7K/10/
This worked for me.
var rDate = (new Date()).toISOString().slice(0, 10).replace(/-/g, "");
Try this.
​var date = new Date();
var year = date.getFullYear().toString();
var month = date.getMonth().toString();
var day = date.getDate().toString();
if (parseInt(month) < 10) month = "0" + month;
if (parseInt(day) < 10) day = "0" + day;
var parsedDate = year + month + day;
(edit)
Improved this function by making the day equate to the day of the month, rather than the day of the week.
How about
date = new Date().toJSON().substr(0,10).split("-")
date = date[0] + date[1] + date[2]
Edit:
This will return the UTC date, not local date...
For local date, you could use:
date = new Date().toLocaleDateString().split("/"); // "M/D/YYYY"
date[0] = date[0].length == 1 ? "0" + date[0] : date[0];
date[1] = date[1].length == 1 ? "0" + date[1] : date[1];
date = date[2] + date[0] + date[1];
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
document.write(curr_year + curr_month + curr_date);
That should give the right date:)

How to get current date in jQuery?

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'

Categories