Get Current Date using JS - javascript

I'm trying to get the current date so I can use it at the ending of this link. My code is almost correct but can't figure out what is going wrong.
Correct Format Example:
**http://zumdb-prod.itg.com/zum/AppServlet?action=aotool&jspURL=clusterTools/toolset.jsp&fegoaltype=RAW&eedbListName=ZUM_CMP_DNS_CMP_Clean&facility=DMOS5-CLUSTER&monthDate=01/09/2022
My results are almost correct but the code returns with the following date 01/0/2022 instead of 01/09/2022
Can someone help me figure out this small bug?
<script>
const getDate = () => {
let newDate = new Date();
let year = newDate.getFullYear();
let month = newDate.getMonth() + 1;
let d = newDate.getDay();
return month + '/' + d + '/' + year;
}
document.getElementById('Ao').src =
'http://zumdb-prod.itg.com/zum/AppServlet?action=aotool&jspURL=clusterTools/toolset.jsp&fegoaltype=RAW&eedbListName=ZUM_CMP_DNS_CMP_Clean&facility=DMOS5-CLUSTER&monthDate='
.concat(getDate());
document.getElementById('MTD').src =
'http://zumdb-prod.itg.com/zum/AppServlet?action=aotoolFe&jspURL=clusterTools/toolsetFe.jsp&fegoaltype=RAW&eedbListName=ZUM_DIFF_TEL_IPD_HTO&facility=DMOS5-CLUSTER&monthDate='
.concat(getDate());
</script>

You should be using getDate() and not getDay(). The latter returns the zero-based day of the week (starting Sunday). You want to get the date of the month.
In order to ensure you get double digits for the month and day, you need to convert those numbers to string first, and then use String.prototype.padStart.
const getDate = () => {
const newDate = new Date();
const year = newDate.getFullYear();
const month = newDate.getMonth() + 1;
const d = newDate.getDate();
return `${month.toString().padStart(2, '0')}/${d.toString().padStart(2, '0')}/${year}`;
}
console.log(getDate());

Here are alternative methods for native date formatting using toLocaleString()
m/d/yyyy
const getDate = () => {
const date = new Date();
return date.toLocaleString().split(",")[0];
}
console.log(getDate());
mm/dd/yyyy
const getDate = () => {
const date = new Date();
return date.toLocaleString('en-US', {
month: '2-digit',
day: '2-digit',
year: 'numeric'
});
}
console.log(getDate());

Related

get the day of the date in text format

Returning a list from the backend. This list is the notifications list. I want to write the date of each element next to it. But I want to write only the day of this date as text. I want these days in abbreviated TR format.
For example;
Sal (TR) = Tue
const stringToDate = (stringDate) => { // stringDate: '16-05-2022'
const dateArray = stringDate.split('-');
return (new Date(dateArray[2], (dateArray[1] - 1).toString().padStart(2, '0'), dateArray[0].padStart(2, '0')));
};
const day = new Date(stringToDate(props.notification?.notificationList?.createdAt));
const notificationDay = day.toLocaleString('tr', { day: 'short' });
console.log(notificationDay);
Use weekday
const notificationDay = day.toLocaleString('tr', { weekday: 'short' });
console.log(notificationDay);

Get next date(YYYY-MM-DD) according to the input date string in jQuery

Consider, I have a date that format is (Year-Month-Date),
adate = "2020-10-02";
Now I would like to create a jQuery function that input adate and return the next_date such like below,
function make_next_date(adate) {
next_date = adate + 1; //"2020-10-03"
return next_date;
}
Function should be work properly for the following input date,
adate = "2021-05-31";
next_date = "2021-06-01";
adate = "2020-12-31";
next_date = "2021-01-01";
adate = "2021-02-28";
next_date = "2021-03-01";
This is just JavaScript. JavaScript has dates. jQuery is not relevant to date manipulation.
function make_next_date(adate) {
next_date = new Date(adate);
next_date.setDate(next_date.getDate() + 1);
return next_date.toISOString().split('T')[0];
}
[
"2021-05-31",
"2020-12-31",
"2021-02-28",
].forEach(date => {
console.log({
date,
out: make_next_date(date)
});
});
function make_next_date(adate) {
const date = new Date(adate);
date.setDate(date.getDate() + 1);
// YEAR
const rYear = date.getFullYear();
// MONTH
let rMonth = date.getMonth() + 1;
rMonth = rMonth < 10 ? `0${rMonth}` : rMonth;
// DATE
let rDate = date.getDate();
rDate = rDate < 10 ? `0${rDate}` : rDate;
return `${rYear}-${rMonth}-${rDate}`;
}
["2021-05-31", "2020-12-31", "2021-02-28"].forEach((date) => {
console.log({
date,
out: make_next_date(date),
});
});
Change your string to date object.
And add 1.
Let date = new Date();
date.SetDate(Date.parseDate(your string + 1);
You can use Date class and padStart function to achieve it.
let adate = "2020-10-02";
function make_next_date(adate) {
const [year, month, day] = adate
.split("-")
.map(item => parseInt(item));
const date = new Date(year, month, day);
date.setDate(date.getDate() + 1);
return [
date.getFullYear(),
date.getMonth().toString().padStart(2, 0),
date.getDate().toString().padStart(2, 0)
].join("-")
}
console.log(make_next_date(adate));
Also, there is a very useful date manipulating package called moment. You can achieve it by just 3 lines of codes using moment.
const moment = require("moment");
const FORMAT = "YYYY-MM-DD";
let adate = "2020-10-02";
function make_next_date(adate) {
return moment(adate, FORMAT)
.add(1, "day")
.format(FORMAT);
}

Suggest Next available date(closest) but don't suggest dates which are in array

I have a list of array exdate which has some date. I want to exclude those dates and suggest the next available date from today. Date should not be random.
const exdate = ["24/08/2020", "8/8/2020"] //dates needs to be excluded [DD/MM/YYYY]
The newly generated date would be "25/08/2020" which is the closest one and not in the array.
This post has a question that is generating a random date using math.random function but my scenario is different.
Iterate inside a while loop and check if exdate contains the current date. If it doesnt contain the date, add 1 day to the current date and check it again. If the current date is not present inside the exdate array, exit the while loop and print the value.
A thing you might consider: What is the expected format of your dates? You should make sure it stays consistent. e.g. dont use leading 0s in front of months. My answer should point you into the right direction.
exdate = ['24/8/2020', '8/8/2020'];
let currDate = new Date();
let dd = currDate.getDate();
let mm = currDate.getMonth() + 1;
let y = currDate.getFullYear();
let dateFormat = dd + '/' + mm + '/' + y;
while (true) {
dd = currDate.getDate();
mm = currDate.getMonth() + 1;
y = currDate.getFullYear();
dateFormat = dd + '/' + mm + '/' + y;
if (!exdate.includes(dateFormat)) break;
currDate.setDate(currDate.getDate() + 1);
}
console.log(dateFormat);
I think this code does what you are after and is quite simple:
import moment from "moment";
// Constants
const dateFormat = 'DD/MM/YYYY'
// Utils
const strToDate = (date) => moment(date, dateFormat)
const dateToStr = (date) => date.format(dateFormat)
const sortByMoment = (a, b) => b.diff(a)
const incrementDate = (date) => date.add(1, 'day')
const isToday = (date) => moment().isSame(date, 'day')
// Data
const exdate = ["17/08/2020", "24/08/2020", "8/8/2020"];
// Implementation
const sortNewestToOldest = (data) => data
.map(strToDate)
.sort(sortByMoment)
const nextAvailableDate = ([head]) => isToday(head) ? [dateToStr(incrementDate(head))] : [dateToStr(moment())]
nextAvailableDate check if todays date is in the exdate list, if yes return tomorrow, else return today. If you also had future dates in there that you need to accomodate for you could expand isToday to be isTodayOrInTheFuture. The moment functions you would need can all be found here.

moment.js concatenate date and time

I have four fields in a form, some containing an initial date and the end date (dd / mm / yyyy) and the others contain the start time and the end time (hh: ss).
The value of these fields I use to get the date and time with moment.js such as this:
initialdate = moment( $('input#start_date').val(), 'DD/MM/YYYY' );
start_time = moment( $('input#start_time').val(), 'HH:mm');
enddate = moment( $('input#enddate').val(), 'DD/MM/YYYY' );
end_time = moment( $('input#end_time').val(), 'HH:mm');
What I intend is to then get the difference in seconds between the two dates, concatenating the starting date and time and the ending date and time. I have tried to do this, but to no avail:
start = initialdate + start_time;
end = enddate + end_time;
tracker = moment.duration( end.diff(start) ).asSeconds();
Concatenate the date and time strings and parse them as one, e.g.
var date = '23/02/2017';
var time = '15:42';
var dateTime = moment(date + ' ' + time, 'DD/MM/YYYY HH:mm');
console.log(dateTime.format('YYYY-MM-DD HH:mm'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>
The fail is trying on concatenate the values, test with something like this:
let initialdate = '2016-10-01';
let start_time = '19:04:10';
let enddate = '2016-10-01';
let end_time = '19:04:20';
let datetimeA = moment(initialdate + " " + start_time);
let datetimeB = moment(enddate + " " + end_time);
console.log(datetimeA.format());
console.log(datetimeB.format());
let datetimeC = datetimeB.diff(datetimeA, 'seconds');
console.log(datetimeC);
[2021] Most elegant solution is:
/* `date` and `time` are instances of Moment */
date = date.set({
hour: time.get('hour'),
minute: time.get('minute'),
second: 0,
millisecond: 0,
});
A much cleaner solution IMO is to use moment's hour and minute getters and setters.
let a = moment()
let b = moment().add(3, 'hour').add(37, 'minute') //b is the time portion
a.hour(b.hour()).minute(b.minute())
Simply use this function
function getCombinedDateObject(date, time) {
let calculatedDateString = '';
if (date && time) {
let utcDate = moment.utc(date);
let utcTime = moment.utc(time);
calculatedDateString = moment(`${utcDate.format('YYYY-MM-DD')} ${utcTime.format("HH:mm:ss z")}`);
}
let finalDateTime = new Date(calculatedDateString);
if (isNaN(finalDateTime.getTime()))
return null;
else
return finalDateTime;
}
My answer is simple,
I just change the time of date as following:
const date = new Date(myDate)
const time = new Date(myTime)
date.setHours(time.getHours())
date.setMinutes(time.getMinutes())

Convert yyyy-MM-dd to MM/dd/yyyy in javascript

This might be a simple solution but I am stuck, basically I need convert an incoming yyyy-MM-dd to MM/dd/yyyy also, if incoming date is nil, then output should also be nil.
Incoming date could be of following format
2015-01-25 or nil
Output date shoud be
01/25/2015 or nil
I was trying one from the following link
Convert Date yyyy/mm/dd to MM dd yyyy but couldn't make it work.
Thanks for any help.
Forgot to mention, the incoming date which comes as nil is of the following format in an xml file
<Through_Date__c xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
So if I get the above format the output should be just be nil
The date toString function has some support for formatting. See this. And you also want to handle the undefined case which I took from here. So, for your case you can just do this:
function format(inputDate) {
var date = new Date(inputDate);
if (!isNaN(date.getTime())) {
// Months use 0 index.
return date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear();
}
}
EDIT: Addressing the comment
If the padding is important you just need to add that in:
var d = date.getDate().toString();
(d[1]?d:"0"+d[0])
I've made an update to the fiddle
Try using RegEx:
var format = function(input) {
var pattern = /(\d{4})\-(\d{2})\-(\d{2})/;
if (!input || !input.match(pattern)) {
return null;
}
return input.replace(pattern, '$2/$3/$1');
};
console.log(format('2015-01-25'));
console.log(format('2000-12-01'));
console.log(format(''));
console.log(format(null));
Using String#split and Array#join, push & shift:
var format = function(input) {
var array = (input || '').toString().split(/\-/g);
array.push(array.shift());
return array.join('/') || null;
};
console.log(format('2015-01-25'));
console.log(format('2000-12-01'));
console.log(format(''));
console.log(format(null));
if you wanna go ghetto style and use easily understandable code, and you dont care about using a date object, try this!
function changeDateFormat(inputDate){ // expects Y-m-d
var splitDate = inputDate.split('-');
if(splitDate.count == 0){
return null;
}
var year = splitDate[0];
var month = splitDate[1];
var day = splitDate[2];
return month + '\\' + day + '\\' + year;
}
var inputDate = '2015-01-25';
var newDate = changeDateFormat(inputDate);
console.log(newDate); // 01/25/2015
you can deal your javascript dates in various formats.
For dd/MM/yyyy you can use
var date = new Date().toLocalDateString()
or
var date = new Date('2021-07-28').toLocalDateString()
output: '28/07/2021'
For MM/dd/yyyy
var date = new Date().toLocaleDateString("en-US", { year: "numeric", month: "2-digit", day: "2-digit" })
or
var date = new Date('2021-07-28').toLocaleDateString("en-US", { year: "numeric", month: "2-digit", day: "2-digit" })
output: '07/28/2021'
Alternatively you can handle custom date formats using following date functions
let date = new Date()
let dateString = [
date.getMonth() + 1,
date.getDate(),
date.getFullYear(),
].join('/')
}
output: 07/28/2021
If your date has not yet been parsed from a string, you can simply rearrange its components:
var s = '2015-01-25';
if (s) {
s = s.replace(/(\d{4})-(\d{1,2})-(\d{1,2})/, function(match,y,m,d) {
return m + '/' + d + '/' + y;
});
}
Thanks guys, I was able to do grab some ideas from all your posts and came up with this code which seems to working fine in my case
if((typeof inStr == 'undefined') || (inStr == null) ||
(inStr.length <= 0)) {
return '';
}
var year = inStr.substring(0, 4);
var month = inStr.substring(5, 7);
var day = inStr.substring(8, 10);
return month + '/' + day + '/' + year;
You can also try the method below using vanilla JS. I have converted the date to a string & parsed it to get the format you're looking for:
function tranformDate(strDate) {
let result = '';
if (date) {
let parts = date.split('-');
result = `${parts[1]}/${parts[2]}/${parts[0]}`;
}
return result;
}
let date = new Date().toISOString().split('T')[0];
console.log('raw date: ' + date);
console.log('formatted date: ' + tranformDate(date));

Categories

Resources