Date changes when setting value - javascript

I'm facing a strange problem, I have a function to get the current date. It may not be the best, but it's ok. I then use the function to set the value of a hidden input:
function gettoday() {
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var out = (day < 10 ? '0' : '') + day + '/' +
(month < 10 ? '0' : '') + month + '/' +
d.getFullYear();
return out;
}
something.attr('value', String(gettoday()));
When I do so the date becomes 31/12/1969. The gettoday() function returns the correct date. Any ideas what could be happening? I tried debugging the call but nothing happens there. The same happens in Chrome or Firefox. Thanks!

You should set the value using val in yyyy-mm-dd format, try the following snippet
function gettoday() {
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var out = d.getFullYear() + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
return out;
}
$('input').val(gettoday());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date">

Related

Unable to get property 'replace' of undefined or null reference?

This code throws error:
Unable to get property 'replace' of undefined or null reference
function formatDate(dateVal) {
var date = new Date(parseInt(dateVal.replace('/Date(', '')))
var month = date.getMonth() + 1;
var day = date.getDate();
var year = date.getFullYear();
return (day.toString().length > 1 ? day : "0" + day) + "/" + (month.toString().length > 1 ? month : "0" + month) + "/" + year;
}
The value being passed to it is null and is in format like /Date(-62135596800000)/.
Well, if you pass a null value, it doesn't have any properties. Make sure you pass the correct value:
function formatDate(dateVal) {
var date = new Date(parseInt(dateVal.replace('/Date(', '')))
var month = date.getMonth() + 1;
var day = date.getDate();
var year = date.getFullYear();
return (day.toString().length > 1 ? day : "0" + day) + "/" + (month.toString().length > 1 ? month : "0" + month) + "/" + year;
}
console.log(formatDate("/Date(-62135596800000)/"));
use default parameters like this formatDate(dateVal = "" ) ,It allows you to set default values for your function parameters if no value is passed or if undefined is passed:
function formatDate(dateVal = "" ) {
var date = new Date(parseInt(dateVal.replace('/Date(', '')))
var month = date.getMonth() + 1;
var day = date.getDate();
var year = date.getFullYear();
return (day.toString().length > 1 ? day : "0" + day) + "/" + (month.toString().length > 1 ? month : "0" + month) + "/" + year;
}
Your issue seems to be that you're expecting a string like "/Date(-62135596800000)/" but are getting something else. So validate the input before calling string methods to parse it, e.g.
function formatDate(dateVal) {
// Test for string in required format
if (!/^\/Date\([+-]?\d{1,16}\)\/$/.test(dateVal)) {
return; // undefined
}
let date = new Date(parseInt(dateVal.replace('/Date(', '')))
let month = date.getMonth() + 1;
let day = date.getDate();
let year = ('000' + date.getFullYear()).slice(-4);
return (day > 9 ? day : "0" + day) + "/" +
(month > 9 ? month : "0" + month) + "/" +
year;
}
// Simple tests
['/Date(-62135596800000)/',
null,
NaN,
'sweet',
1561853541934,
'/Date(1561853541934)/'].forEach(
v => console.log(v + ': ' + formatDate(v))
);
Then in the caller, you can test if you got back a string (success) or undefined, which indicates invalid input that you'll need to deal with.

date formatting issues. js jquery

Date formatting issues after July.the date shown is a weekly format. any help will be highly appreciated.the date is working fine just that not working as expected
$(document).ready(function () {
var curr = new Date; // get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var last = first + 6; // last day is the first day + 6
var startDate = new Date(curr.setDate(first));
startDate = ((startDate.getMonth() + 1) < 10 ? '0'
: '')
+ (startDate.getMonth() + 1)
+ "/"
+ ((startDate.getDate() < 10 ? '0' : '') + startDate
.getDate())
+ "/"
just change this code
var endDate = new Date(startDate);
endDate.setDate(startDate.getDate() + 6);
You can check below working code.
$(document).ready(function () {
//var curr = new Date('2020-02-29'); // for leap
var curr = new Date();// get current date
var first = curr.getDate() - curr.getDay(); // First day is the day of the month - the day of the week
var startDate = new Date(curr.setDate(first));
var endDate = new Date(startDate);
endDate.setDate(startDate.getDate() + 6);
startDate = ((startDate.getMonth() + 1) < 10 ? '0'
: '')
+ (startDate.getMonth() + 1)
+ "/"
+ ((startDate.getDate() < 10 ? '0' : '') + startDate
.getDate())
+ "/"
+ startDate.getFullYear();
endDate = ((endDate.getMonth() + 2) < 10 ? '0' : '')
//this might have some flaws if i make it to 2 it works but this is short term fix and will break again
+ (endDate.getMonth() + 1)
+ "/"
+ ((endDate.getDate() < 10 ? '0' : '') + endDate
.getDate())
+ "/"
+ endDate.getFullYear();
document.getElementById("ok").innerHTML = startDate;
document.getElementById("napa").innerHTML = endDate;
$(".next")
.click(
function () {
document.getElementById("tabletbody").innerHTML = "";
var startdt = new Date($('#ok')
.text());
startdt.setDate(startdt
.getDate() + 7);
document.getElementById("ok").innerHTML = (getDateFormat(startdt));
var enddt = new Date($('#napa')
.text());
enddt
.setDate(enddt
.getDate() + 7);
document.getElementById("napa").innerHTML = (getDateFormat(enddt));
updateCompass();
return false;
});
function getDateFormat(d) {
var month = ((d.getMonth() + 1) < 10 ? '0' : '')
+ (d.getMonth() + 1);
var dd = (d.getDate() < 10 ? '0' : '')
+ d.getDate();
return month + "/" + dd + "/" + d.getFullYear();
}
$(".previous").click(function () {
document.getElementById("tabletbody").innerHTML = "";
var startdt = new Date($('#ok').text());
startdt.setDate(startdt.getDate() - 7);
$('#ok').text(getDateFormat(startdt));
var enddt = new Date($('#napa').text());
enddt.setDate(enddt.getDate() - 7);
$('#napa').text(getDateFormat(enddt));
updateCompass();
return false;
});
});
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div id="ok"></div>
<div id="napa"></div>

Datetime comparison in JavaScript/jQuery

I have these two calendar pickers that chooses the date for you, one for arrival and one of departed.
If the user chooses a day in departed calendar that is earlier than the one in arrival calendar, the calendar picker should be either disabled or when choosen - ignore it.
For example: arrival is 2017-03-08, choosen and read in the textbox and same for departed. If I try to pick 2017-03-07 for departed, it should not allow it and not be read in the textbox.
How is this possible with javascript/jquery?
My code:
var CalendarTwo;
function onPopupTxtArrivalDateChanged(sender) { //Function that reads arrival date
var txtArrival = $("#txtArrivalDate");
var date = new Date(sender.getSelectedDate());
var textDate = date.getFullYear() + "-" + (date.getMonth() <= 9 ? "0" + (date.getMonth() + 1)
: (date.getMonth() + 1)) + "-" + (date.getDate() <= 9 ? "0" + date.getDate() : date.getDate());
txtArrival.val(textDate);
onChange(sender, txtArrival, $("#txtDepartureDate")[0], CalendarTwo);
}
function onPopupTxtDepartureDateChanged(sender) { //Function that reads departed date
var txtDeparture = $("#txtDepartureDate");
var date = new Date(sender.getSelectedDate());
var textDate = date.getFullYear() + "-" + (date.getMonth() <= 9 ? "0" + (date.getMonth() + 1)
: (date.getMonth() + 1)) + "-" + (date.getDate() <= 9 ? "0" + date.getDate() : date.getDate());
CalendarTwo = sender;
txtDeparture.val(textDate);
}
function onChange(sender, txt, departed, calendarTwo) { //Function that checks that arrival date and departed is equal
var txtDate = $(txt).val();
var date = new Date(txtDate);
if (departed != undefined) {
CalendarTwo = calendarTwo;
var departedDate = new Date($(departed).val());
if (departedDate < date) {
calendarTwo.setSelectedDate(date);
departed.value = txtDate;
}
}
sender.SetSelectedDate(date);
}

Formatting Date in javascript [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 6 years ago.
I want date with this format : '%Y-%m-%dT%H:%M:%S+0000'. I wrote a function but still asking myself if there is not better way to do this.
This is my function :
function formatDate() {
var d = new Date();
var year = d.getMonth() + 1;
var day = d.getDate();
var month = d.getMonth() + 1;
var hour = d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
var date = d.getFullYear() + "-" + (month < 10 ? '0' + month : month) + "-" +
(day < 10 ? '0' + day : day) +
"T" + (hour < 10 ? '0' + hour : hour) + ":" + (min < 10 ? '0' + min : min) + ":" + (sec < 10 ? '0' + sec : sec) + "+0000";
return date;
}
Any ideal on how to do this with less code ?
It can be done in one line. I made two lines to make it simpler. Combine line 2 and 3.
var d = new Date();
date = d.toISOString().toString();
var formattedDate = date.substring(0, date.lastIndexOf(".")) + "+0000";
console.log(formattedDate);
Use moment.js.
moment().format('YYYY-MM-DDTh:mm:ss+0000')
JSBIN
console.log(moment().format('YYYY-MM-DDTh:mm:ss+0000'))
<script src="https://cdn.jsdelivr.net/momentjs/2.14.1/moment-with-locales.min.js"></script>
var d = new Date();
var dateString = d.getUTCFullYear() +"-"+ (d.getUTCMonth()+1) +"-"+ d.getUTCDate() + " " + d.getUTCHours() + ":" + d.getUTCMinutes() + ":" + d.getUTCSeconds()+"+0000";
getUTCMonth returns 0 - 11, so want to add one before you convert to string.

How do I get Month and Date of JavaScript in 2 digit format?

When we call getMonth() and getDate() on date object, we will get the single digit number.
For example :
For january, it displays 1, but I need to display it as 01. How to do that?
("0" + this.getDate()).slice(-2)
for the date, and similar:
("0" + (this.getMonth() + 1)).slice(-2)
for the month.
If you want a format like "YYYY-MM-DDTHH:mm:ss", then this might be quicker:
var date = new Date().toISOString().substr(0, 19);
// toISOString() will give you YYYY-MM-DDTHH:mm:ss.sssZ
Or the commonly used MySQL datetime format "YYYY-MM-DD HH:mm:ss":
var date2 = new Date().toISOString().substr(0, 19).replace('T', ' ');
Why not use padStart ?
padStart(targetLength, padString) where
targetLength is 2
padString is 0
// Source: https://stackoverflow.com/a/50769505/2965993
var dt = new Date();
year = dt.getFullYear();
month = (dt.getMonth() + 1).toString().padStart(2, "0");
day = dt.getDate().toString().padStart(2, "0");
console.log(year + '/' + month + '/' + day);
This will always return 2 digit numbers even if the month or day is less than 10.
Notes:
This will only work with Internet Explorer if the js code is transpiled using babel.
getFullYear() returns the 4 digit year and doesn't require padStart.
getMonth() returns the month from 0 to 11.
1 is added to the month before padding to keep it 1 to 12.
getDate() returns the day from 1 to 31.
The 7th day will return 07 and so we do not need to add 1 before padding the string.
Example for month:
function getMonth(date) {
var month = date.getMonth() + 1;
return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}
You can also extend Date object with such function:
Date.prototype.getMonthFormatted = function() {
var month = this.getMonth() + 1;
return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}
The best way to do this is to create your own simple formatter (as below):
getDate() returns the day of the month (from 1-31)
getMonth() returns the month (from 0-11) < zero-based, 0=January, 11=December
getFullYear() returns the year (four digits) < don't use getYear()
function formatDateToString(date){
// 01, 02, 03, ... 29, 30, 31
var dd = (date.getDate() < 10 ? '0' : '') + date.getDate();
// 01, 02, 03, ... 10, 11, 12
var MM = ((date.getMonth() + 1) < 10 ? '0' : '') + (date.getMonth() + 1);
// 1970, 1971, ... 2015, 2016, ...
var yyyy = date.getFullYear();
// create the format you want
return (dd + "-" + MM + "-" + yyyy);
}
I would do this:
var date = new Date(2000, 0, 9);
var str = new Intl.DateTimeFormat('en-US', {
month: '2-digit',
day: '2-digit',
year: 'numeric'
}).format(date);
console.log(str); // prints "01/09/2000"
The following is used to convert db2 date format
i.e YYYY-MM-DD using ternary operator
var currentDate = new Date();
var twoDigitMonth=((currentDate.getMonth()+1)>=10)? (currentDate.getMonth()+1) : '0' + (currentDate.getMonth()+1);
var twoDigitDate=((currentDate.getDate())>=10)? (currentDate.getDate()) : '0' + (currentDate.getDate());
var createdDateTo = currentDate.getFullYear() + "-" + twoDigitMonth + "-" + twoDigitDate;
alert(createdDateTo);
Just another example, almost one liner.
var date = new Date();
console.log( (date.getMonth() < 9 ? '0': '') + (date.getMonth()+1) );
function monthFormated(date) {
//If date is not passed, get current date
if(!date)
date = new Date();
month = date.getMonth();
// if month 2 digits (9+1 = 10) don't add 0 in front
return month < 9 ? "0" + (month+1) : month+1;
}
If it might spare some time I was looking to get:
YYYYMMDD
for today, and got along with:
const dateDocumentID = new Date()
.toISOString()
.substr(0, 10)
.replace(/-/g, '');
function monthFormated() {
var date = new Date(),
month = date.getMonth();
return month+1 < 10 ? ("0" + month) : month;
}
This was my solution:
function leadingZero(value) {
if (value < 10) {
return "0" + value.toString();
}
return value.toString();
}
var targetDate = new Date();
targetDate.setDate(targetDate.getDate());
var dd = targetDate.getDate();
var mm = targetDate.getMonth() + 1;
var yyyy = targetDate.getFullYear();
var dateCurrent = leadingZero(mm) + "/" + leadingZero(dd) + "/" + yyyy;
Using Moment.js it can be done like that:
moment(new Date(2017, 1, 1)).format('DD') // day
moment(new Date(2017, 1, 1)).format('MM') // month
const today = new Date().toISOString()
const fullDate = today.split('T')[0];
console.log(fullDate) //prints YYYY-MM-DD
Not an answer but here is how I get the date format I require in a variable
function setDateZero(date){
return date < 10 ? '0' + date : date;
}
var curr_date = ev.date.getDate();
var curr_month = ev.date.getMonth() + 1;
var curr_year = ev.date.getFullYear();
var thisDate = curr_year+"-"+setDateZero(curr_month)+"-"+setDateZero(curr_date);
Hope this helps!
Ternary Operator Solution
A simple ternary operator can add a "0" before the number if the month or day is less than 10 (assuming you need this information for use in a string).
let month = (date.getMonth() < 10) ? "0" + date.getMonth().toString() : date.getMonth();
let day = (date.getDate() < 10) ? "0" + date.getDate().toString() : date.getDate();
The more modern approach perhaps, using "padStart"
const now = new Date();
const day = `${now.getDate()}`.padStart(2, '0');
const month = `${now.getMonth()}`.padStart(2, '0');
const year = now.getFullYear();
then you can build as a template string if you wish:
`${day}/${month}/${year}`
Tip from MDN :
function date_locale(thisDate, locale) {
if (locale == undefined)
locale = 'fr-FR';
// set your default country above (yes, I'm french !)
// then the default format is "dd/mm/YYY"
if (thisDate == undefined) {
var d = new Date();
} else {
var d = new Date(thisDate);
}
return d.toLocaleDateString(locale);
}
var thisDate = date_locale();
var dayN = thisDate.slice(0, 2);
var monthN = thisDate.slice(3, 5);
console.log(dayN);
console.log(monthN);
http://jsfiddle.net/v4qcf5x6/
new Date().getMonth() method returns the month as a number (0-11)
You can get easily correct month number with this function.
function monthFormatted() {
var date = new Date(),
month = date.getMonth();
return month+1 < 10 ? ("0" + month) : month;
}
I would suggest you use a different library called Moment https://momentjs.com/
This way you are able to format the date directly without having to do extra work
const date = moment().format('YYYY-MM-DD')
// date: '2020-01-04'
Make sure you import moment as well to be able to use it.
yarn add moment
# to add the dependency
import moment from 'moment'
// import this at the top of the file you want to use it in
Hope this helps :D
How it easy?
new Date().toLocaleString("en-US", { day: "2-digit" })
Another options are available such:
weekday
year
month
More info here.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString#using_options
function GetDateAndTime(dt) {
var arr = new Array(dt.getDate(), dt.getMonth(), dt.getFullYear(),dt.getHours(),dt.getMinutes(),dt.getSeconds());
for(var i=0;i<arr.length;i++) {
if(arr[i].toString().length == 1) arr[i] = "0" + arr[i];
}
return arr[0] + "." + arr[1] + "." + arr[2] + " " + arr[3] + ":" + arr[4] + ":" + arr[5];
}
And another version here https://jsfiddle.net/ivos/zcLxo8oy/1/, hope to be useful.
var dt = new Date(2016,5,1); // just for the test
var separator = '.';
var strDate = (dt.getFullYear() + separator + (dt.getMonth() + 1) + separator + dt.getDate());
// end of setup
strDate = strDate.replace(/(\b\d{1}\b)/g, "0$1")
The answers here were helpful, however I need more than that: not only month, date, month, hours & seconds, for a default name.
Interestingly, though prepend of "0" was needed for all above, " + 1" was needed only for month, not others.
As example:
("0" + (d.getMonth() + 1)).slice(-2) // Note: +1 is needed
("0" + (d.getHours())).slice(-2) // Note: +1 is not needed
My solution:
function addLeadingChars(string, nrOfChars, leadingChar) {
string = string + '';
return Array(Math.max(0, (nrOfChars || 2) - string.length + 1)).join(leadingChar || '0') + string;
}
Usage:
var
date = new Date(),
month = addLeadingChars(date.getMonth() + 1),
day = addLeadingChars(date.getDate());
jsfiddle: http://jsfiddle.net/8xy4Q/1/
var net = require('net')
function zeroFill(i) {
return (i < 10 ? '0' : '') + i
}
function now () {
var d = new Date()
return d.getFullYear() + '-'
+ zeroFill(d.getMonth() + 1) + '-'
+ zeroFill(d.getDate()) + ' '
+ zeroFill(d.getHours()) + ':'
+ zeroFill(d.getMinutes())
}
var server = net.createServer(function (socket) {
socket.end(now() + '\n')
})
server.listen(Number(process.argv[2]))
if u want getDate() function to return the date as 01 instead of 1, here is the code for it....
Lets assume Today's date is 01-11-2018
var today = new Date();
today = today.getFullYear()+ "-" + (today.getMonth() + 1) + "-" + today.getDate();
console.log(today); //Output: 2018-11-1
today = today.getFullYear()+ "-" + (today.getMonth() + 1) + "-" + ((today.getDate() < 10 ? '0' : '') + today.getDate());
console.log(today); //Output: 2018-11-01
I wanted to do something like this and this is what i did
p.s. i know there are right answer(s) on top, but just wanted to add something of my own here
const todayIs = async () =>{
const now = new Date();
var today = now.getFullYear()+'-';
if(now.getMonth() < 10)
today += '0'+now.getMonth()+'-';
else
today += now.getMonth()+'-';
if(now.getDay() < 10)
today += '0'+now.getDay();
else
today += now.getDay();
return today;
}
If you'll check smaller than 10, you haven't to create a new function for that. Just assign a variable into brackets and return it with ternary operator.
(m = new Date().getMonth() + 1) < 10 ? `0${m}` : `${m}`
currentDate(){
var today = new Date();
var dateTime = today.getFullYear()+'-'+
((today.getMonth()+1)<10?("0"+(today.getMonth()+1)):(today.getMonth()+1))+'-'+
(today.getDate()<10?("0"+today.getDate()):today.getDate())+'T'+
(today.getHours()<10?("0"+today.getHours()):today.getHours())+ ":" +
(today.getMinutes()<10?("0"+today.getMinutes()):today.getMinutes())+ ":" +
(today.getSeconds()<10?("0"+today.getSeconds()):today.getSeconds());
return dateTime;
},

Categories