how to get my month and date in two digit formats - javascript

i am trying to calculate my date to 364 days using javascript, this works as i got a snippet online that functions the way i expect.
But now i have noticed that the date format is in 1 digit.
meaning for the present month instead of september to be written as "09" its wriiten as "9", i am honestly not a javascript king so am looking for help on this.
This is what i am presently trying that gives me a 1 digit date
<script type='text/javascript'>//<![CDATA[
function getdate() {
var tt = document.getElementById('inputDater').value;
var date = new Date(tt);
var newdate = new Date(date);
newdate.setDate(newdate.getDate() + 364);
var dd = newdate.getDate();
var mm = newdate.getMonth() + 1;
var y = newdate.getFullYear();
var someFormattedDate = y + '-' + mm + '-' + dd;
document.getElementById('follow').value = someFormattedDate;
}
//]]>
</script>
so onclick of my button i call my function, please can someone enlighten me thanks

Format the month into 2 digit format using the following method.
mm = ("0" + mm).slice(-2);
var someFormattedDate = y + '-' + mm + '-' + dd;
or use the following function, which is simple and you can use for date too
function pad(d) {
return (d < 10) ? '0' + d.toString() : d.toString();
}
mm = pad(mm);

you can change the line in your code from
var mm = newdate.getMonth() + 1;
to
var mm = newdate.getMonth()<9 ? '0'+(newdate.getMonth()+ 1) : newdate.getMonth()+1;

Hope this helps
function getDate() {
//var tt = document.getElementById('inputDater').value;
var date = new Date();//(tt);
var newdate = new Date(date);
newdate.setDate(newdate.getDate() + 364);
var dd = newdate.getDate();
var mm = newdate.getMonth() + 1;
var y = newdate.getFullYear();
//2 digit format
dd = dd.toString().length == 1 ? '0' + dd : dd;
mm = mm.toString().length == 1 ? '0' + mm : mm;
var someFormattedDate = y + '-' + mm + '-' + dd;
console.log(someFormattedDate);
};
getDate();

Related

Issue removing 1 month from date - Get month 0 [duplicate]

This question already has answers here:
Adding months to a Date in JavaScript [duplicate]
(2 answers)
Closed 4 years ago.
I have this code which works fine. It gives me todays date in a specific format.
function fetchTime() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var today = yyyy + '-' + mm + '-' + dd;
return (today);
}
I'm also trying to get today's date minus 1 month. I thought this would be simple, I just removed the +1. So I have this code:
function fetchTime() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth();
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var today = yyyy + '-' + mm + '-' + dd;
return (today);
}
This gives me the output 2019-00-17 which should be 2018-12-17
Can anyone tell me the right way to do this? My question is specific to getting the date out in the required format, whereas most examples I have seen do not output the right format as part of the date change.
I would separate the formatting from the fetching. You could make your existing formatting function take an optional parameter that defaults to today, so you could call it like you already were for today's date.
function formatTime(date) {
var dateToFormat = date || new Date();
var dd = dateToFormat.getDate();
var mm = dateToFormat.getMonth() + 1;
var yyyy = dateToFormat.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
return (yyyy + '-' + mm + '-' + dd);
}
Then you could also call it with today's date minus a month or any other date
formatTime(); //will default to today
var today = new Date();
formatTime(addMonths(today,-1)); //format last month's date
As pointed out by RobG in the comments you would need to implement an addMonths function as in Adding months to a Date in JavaScript
function addMonths(date, months) {
var d = date.getDate();
date.setMonth(date.getMonth() + +months);
if (date.getDate() != d) {
date.setDate(0);
}
return date;
}
For substracting in moment.js:
moment().subtract(1, 'months').format("DD-MM-YYYY")
Documentation:
http://momentjs.com/docs/#/manipulating/subtract/
You should subtract months by getting the current month, then subtracting the number of months you want and then updating the date variable like this.
function fetchTime() {
var today = new Date();
today.setMonth(today.getMonth() - 1);
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var today = yyyy + '-' + mm + '-' + dd;
return (today);
}
Because your desired format is an ISO 8601 date, you could use JavaScript's .toISOString. You are only concerned with the first 10 characters though (not time), so you'd want to add .substring(0,10).
Date.prototype.toISODateString = function() { return this.toISOString().substring(0,10); }
Date.prototype.addMonths = function(val) { this.setMonth(this.getMonth()+val); return this;}
var date = new Date();
var todayFormatted = date.toISODateString();
console.log(todayFormatted);
var lastMonthFormatted = date.addMonths(-1).toISODateString();
console.log(lastMonthFormatted);
I've made the formatting steps a function called toISODateString() and added it to the Date prototype, which is a fancy way of saying "You can chain .toISODateString() to any Date now".
To set the date back a month, I've used .setMonth(). I also turned this into a function called addMonths.
Use the same code, but remove a month. Example:
function fetchTime() {
var today = new Date();
today.setMonth(today.getMonth() - 1);
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var today = yyyy + '-' + mm + '-' + dd;
return (today);
}

Convert string to date and add 5 days to it

I have a string like so
"2014-10-29"
and Now I need to convert it to a date and add 5 days to it.
I have this code that adds 5 days to the current date, but how would I convert that string to a date and add 5 days to it?
var newDate = new Date();
newDate.setDate(newDate.getDate() + 5);
var yyyy = newDate.getFullYear().toString();
var mm = (newDate.getMonth() + 1).toString();
var dd = newDate.getDate().toString();
var mmChars = mm.split('');
var ddChars = dd.split('');
var newClosingDate = yyyy + '-' + (mmChars[1] ? mm : "0" + mmChars[0]) + '-' + (ddChars[1] ? dd : "0" + ddChars[0]);
Pass the string in to the Date constructor:
var newDate = new Date("2014-10-29");
newDate.setDate(newDate.getDate() + 5);
var yyyy = newDate.getFullYear().toString();
var mm = (newDate.getMonth() + 1).toString();
var dd = newDate.getDate().toString();
var mmChars = mm.split('');
var ddChars = dd.split('');
var newClosingDate = yyyy + '-' + (mmChars[1] ? mm : "0" + mmChars[0]) + '-' + (ddChars[1] ? dd : "0" + ddChars[0]);
console.log(newDate);
You could also use the wonderful library called moment.js - it makes working with dates in JavaScript an absolute breeze. Especially converting them back and forth to/from strings.
With your date and using moment, you could do this for example:
var stringFormat = 'YYYY-MM-DD',
date = moment('2014-10-29', 'YYYY-MM-DD');
date.add(5, 'days');
console.log(date.format(stringFormat);
This will print out the string in the same format as you put in.

Adding 1 Year to a Date with JavaScript

I have the following date:
2014-10-29
I am trying to add one year to the date (not 365 days, but 1 year):
var newDate = new Date('2014-10-29');
newDate.setDate(newDate.getFullYear() + 1);
var yyyy = newDate.getFullYear().toString();
var mm = (newDate.getMonth() + 1).toString();
var dd = newDate.getDate().toString();
var mmChars = mm.split('');
var ddChars = dd.split('');
var newClosingDate = yyyy + '-' + (mmChars[1] ? mm : "0" + mmChars[0]) + '-' + (ddChars[1] ? dd : "0" + ddChars[0]);
This returns 2020-04-06, which is obviously wrong.
What am I doing wrong here?
var date = new Date("2014-10-29");
date.setFullYear(date.getFullYear() + 1);

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'

Get date for every Thursday in the year Javascript

Given a day of the week (var day) the code below will print the date of each
day in the year starting from today. Since 4 = Thursday, I will get a list
of all the Thursdays left in the year. I was just curious if there was some
'neater' way to accomplish this?
var day = 4;
var date = new Date();
var nextYear = date.getFullYear() + 1;
while(date.getDay() != day)
{
date.setDate(date.getDate() + 1)
}
while(date.getFullYear() < nextYear)
{
var yyyy = date.getFullYear();
var mm = (date.getMonth() + 1);
mm = (mm < 10) ? '0' + mm : mm;
var dd = date.getDate();
dd = (dd < 10) ? '0' + dd : dd;
console.log(yyyy + '-' + mm + '-' + dd)
date.setDate(date.getDate() + 7);
}
Output:
2011-02-10
2011-02-17
2011-02-24
2011-03-03
2011-03-10
..etc
Well, it would look a lot prettier if you used Datejs.
var thursday = Date.today().next().thursday(),
nextYear = Date.next().january().set({day: 1}),
format = 'yyyy-MM-dd';
while (thursday.isBefore(nextYear))
{
console.log(thursday.toString(format));
thursday = thursday.add(7).days();
}
See also http://code.google.com/p/datejs/.

Categories