Moment.Js date to week & year - javascript

hi I would like to use moment js to pass the week and year number and he returns me "startOf" & "endOf" Step type Week = 22 Year = 2021and I would like him to
return
startOf = 31/05/2021
endOf = 06/06/2021
var startOfWeek = moment().startOf('week').toDate();
var endOfWeek = moment().endOf('week').toDate();

let starDay = moment('2021').add(1, 'weeks').startOf('week').format('DD MM YYYY');
let endDay = moment('2021').add(1, 'weeks').endtOf('week').format('DD MM YYYY');

Related

String to Date with date, hours, minutes and seconds with Typescript [duplicate]

How can I convert a string to a Date object in JavaScript?
var st = "date in some format"
var dt = new Date();
var dt_st = // st in Date format, same as dt.
The best string format for string parsing is the date ISO format together with the JavaScript Date object constructor.
Examples of ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.
But wait! Just using the "ISO format" doesn't work reliably by itself. String are sometimes parsed as UTC and sometimes as localtime (based on browser vendor and version). The best practice should always be to store dates as UTC and make computations as UTC.
To parse a date as UTC, append a Z - e.g.: new Date('2011-04-11T10:20:30Z').
To display a date in UTC, use .toUTCString(),
to display a date in user's local time, use .toString().
More info on MDN | Date and this answer.
For old Internet Explorer compatibility (IE versions less than 9 do not support ISO format in Date constructor), you should split datetime string representation to it's parts and then you can use constructor using datetime parts, e.g.: new Date('2011', '04' - 1, '11', '11', '51', '00'). Note that the number of the month must be 1 less.
Alternate method - use an appropriate library:
You can also take advantage of the library Moment.js that allows parsing date with the specified time zone.
Unfortunately I found out that
var mydate = new Date('2014-04-03');
console.log(mydate.toDateString());
returns "Wed Apr 02 2014". I know it sounds crazy, but it happens for some users.
The bulletproof solution is the following:
var parts ='2014-04-03'.split('-');
// Please pay attention to the month (parts[1]); JavaScript counts months from 0:
// January - 0, February - 1, etc.
var mydate = new Date(parts[0], parts[1] - 1, parts[2]);
console.log(mydate.toDateString());
var st = "26.04.2013";
var pattern = /(\d{2})\.(\d{2})\.(\d{4})/;
var dt = new Date(st.replace(pattern,'$3-$2-$1'));
And the output will be:
dt => Date {Fri Apr 26 2013}
function stringToDate(_date,_format,_delimiter)
{
var formatLowerCase=_format.toLowerCase();
var formatItems=formatLowerCase.split(_delimiter);
var dateItems=_date.split(_delimiter);
var monthIndex=formatItems.indexOf("mm");
var dayIndex=formatItems.indexOf("dd");
var yearIndex=formatItems.indexOf("yyyy");
var month=parseInt(dateItems[monthIndex]);
month-=1;
var formatedDate = new Date(dateItems[yearIndex],month,dateItems[dayIndex]);
return formatedDate;
}
stringToDate("17/9/2014","dd/MM/yyyy","/");
stringToDate("9/17/2014","mm/dd/yyyy","/")
stringToDate("9-17-2014","mm-dd-yyyy","-")
Recommendation: I recommend to use a package for dates that contains a lot of formats because the timezone and format time management is really a big problem, moment js solve a lot of formats. You could parse easily date from a simple string to date but I think that is a hard work to support all formats and variations of dates.
Update: Moment is now deprecated, A good alternative for moment is datefns https://date-fns.org/
moment.js (http://momentjs.com/) is a complete and good package for use dates and supports ISO 8601 strings.
You could add a string date and format.
moment("12-25-1995", "MM-DD-YYYY");
And you could check if a date is valid.
moment("not a real date").isValid(); //Returns false
Some display examples
let dt = moment("02-01-2019", "MM-DD-YYYY");
console.log(dt.fromNow()+' |'+dt.format('LL'))
// output: "3 months ago | February 1, 2019"
See documentation
http://momentjs.com/docs/#/parsing/string-format/
Pass it as an argument to Date():
var st = "date in some format"
var dt = new Date(st);
You can access the date, month, year using, for example: dt.getMonth().
If you can use the terrific luxon library you can easily parse your date using e.g.
var luxonDate = DateTime.fromISO("2014-09-15T09:00:00");
and can access the JS date object via
luxonDate().toJSDate();
The old answer used MomentJS
var momentDate = moment("2014-09-15 09:00:00");
momentDate ().toDate();
For those who are looking for a tiny and smart solution:
String.prototype.toDate = function(format)
{
var normalized = this.replace(/[^a-zA-Z0-9]/g, '-');
var normalizedFormat= format.toLowerCase().replace(/[^a-zA-Z0-9]/g, '-');
var formatItems = normalizedFormat.split('-');
var dateItems = normalized.split('-');
var monthIndex = formatItems.indexOf("mm");
var dayIndex = formatItems.indexOf("dd");
var yearIndex = formatItems.indexOf("yyyy");
var hourIndex = formatItems.indexOf("hh");
var minutesIndex = formatItems.indexOf("ii");
var secondsIndex = formatItems.indexOf("ss");
var today = new Date();
var year = yearIndex>-1 ? dateItems[yearIndex] : today.getFullYear();
var month = monthIndex>-1 ? dateItems[monthIndex]-1 : today.getMonth()-1;
var day = dayIndex>-1 ? dateItems[dayIndex] : today.getDate();
var hour = hourIndex>-1 ? dateItems[hourIndex] : today.getHours();
var minute = minutesIndex>-1 ? dateItems[minutesIndex] : today.getMinutes();
var second = secondsIndex>-1 ? dateItems[secondsIndex] : today.getSeconds();
return new Date(year,month,day,hour,minute,second);
};
Example:
"22/03/2016 14:03:01".toDate("dd/mm/yyyy hh:ii:ss");
"2016-03-29 18:30:00".toDate("yyyy-mm-dd hh:ii:ss");
Just new Date(st);
Assuming that it's the proper format.
new Date(2000, 10, 1) will give you "Wed Nov 01 2000 00:00:00 GMT+0100 (CET)"
See that 0 for month gives you January
If you want to convert from the format "dd/MM/yyyy". Here is an example:
var pattern = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var arrayDate = stringDate.match(pattern);
var dt = new Date(arrayDate[3], arrayDate[2] - 1, arrayDate[1]);
This solution works in IE versions less than 9.
Timestamps should be casted to a Number
var ts = '1471793029764';
ts = Number(ts); // cast it to a Number
var date = new Date(ts); // works
var invalidDate = new Date('1471793029764'); // does not work. Invalid Date
That's the best and simpler solution in my view:
Just concatenate your date string (using ISO format) with "T00:00:00" in the end and use the JavaScript Date() constructor, like the example below.
const dateString = '2014-04-03'
var mydate = new Date(dateString + "T00:00:00");
console.log(mydate.toDateString());
And just a few details about the solution above (but optional reading):
In ISO format, if you provide time and Z is not present in the end of
string, the date will be local time zone instead of UTC time
zone. That means, when setting a date in this way, without
specifying the time zone, JavaScript will use the local browser's time
zone. And when getting a date, without specifying the time zone
as well, the result is also converted to the browser's time zone. And,
by default, almost every date method in JavaScript (except one)
gives you a date/time in local time zone as well (you only get UTC if
you specify UTC). So, using in local/browser time zone you probably
won't get unwanted results because difference between your
local/browse time zone and the UTC time zone, which is one of the main
complaints with date string conversion. But if you will use this
solution, understand your context and be aware of what you are doing.
And also be careful that omitting T or Z in a date-time string
can give different results in different browsers.
Important to note that the example above will give you exactly the same return to this example below, that is the second most voted answer in this question:
var parts ='2014-04-03'.split('-');
// Please pay attention to the month (parts[1]); JavaScript counts months from 0:
// January - 0, February - 1, etc.
var mydate = new Date(parts[0], parts[1] - 1, parts[2]);
console.log(mydate.toDateString());
The main difference is that the first example provided here is simpler and even more error proof than the second one (at least in my view, as explained below).
Because if you call the JavaScript Date() constructor date with just one date-string argument in ISO format (first example), it doesn't accept values above its logical limit (so, if you give 13 as month or 32 as day, you get Invalid Date).
But when you use the same constructor with multiple date-arguments (second example), parameters above it logical limit will be adjusted to the adjacent value and you won't get Invalid Date Error (so, if you give 13 as month, it will adjust to 1, instead of give you an Invalid Date).
Or an alternative (and third) solution would be mix both, use the first example just to validate the date-string and if it is valid use the second example (so you avoid possible browsers inconsistences of the first example and at the same time avoid the permission of parameters above it logical limit of the second example).
Like so (accepting partial dates as well):
function covertStringToDate(dateString) {
//dateString should be in ISO format: "yyyy-mm-dd", "yyyy-mm" or "yyyy"
if(new Date(dateString).toString() === "Invalid Date") {
return false
} else {
const onlyNumbers = dateString.replace(/\D/g, "");
const year = onlyNumbers.slice(0,4)
const month = onlyNumbers.slice(4,6)
const day = onlyNumbers.slice(6,8)
if(!month){
return(new Date(year))
} else if (!day) {
return(new Date(year, month - 1))
} else {
return(new Date(year, month - 1, day))
}
}
}
And a fourth alternative (and last suggestion) would be to use an appropriate third library (like moment or date-fns)
References:
https://www.w3schools.com/js/js_date_formats.asp
https://css-tricks.com/everything-you-need-to-know-about-date-in-javascript/
https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Date#parameters
Date.parse almost gets you what you want. It chokes on the am/pm part, but with some hacking you can get it to work:
var str = 'Sun Apr 25, 2010 3:30pm',
timestamp;
timestamp = Date.parse(str.replace(/[ap]m$/i, ''));
if(str.match(/pm$/i) >= 0) {
timestamp += 12 * 60 * 60 * 1000;
}
Performance
Today (2020.05.08) I perform tests for chosen solutions - for two cases: input date is ISO8601 string (Ad,Bd,Cd,Dd,Ed) and input date is timestamp (At, Ct, Dt). Solutions Bd,Cd,Ct not return js Date object as results, but I add them because they can be useful but I not compare them with valid solutions. This results can be useful for massive date parsing.
Conclusions
Solution new Date (Ad) is 50-100x faster than moment.js (Dd) for all browsers for ISO date and timestamp
Solution new Date (Ad) is ~10x faster than parseDate (Ed)
Solution Date.parse(Bd) is fastest if wee need to get timestamp from ISO date on all browsers
Details
I perform test on MacOs High Sierra 10.13.6 on Chrome 81.0, Safari 13.1, Firefox 75.0. Solution parseDate (Ed) use new Date(0) and manually set UTC date components.
let ds = '2020-05-14T00:00Z'; // Valid ISO8601 UTC date
let ts = +'1589328000000'; // timestamp
let Ad = new Date(ds);
let Bd = Date.parse(ds);
let Cd = moment(ds);
let Dd = moment(ds).toDate();
let Ed = parseDate(ds);
let At = new Date(ts);
let Ct = moment(ts);
let Dt = moment(ts).toDate();
log = (n,d) => console.log(`${n}: ${+d} ${d}`);
console.log('from date string:', ds)
log('Ad', Ad);
log('Bd', Bd);
log('Cd', Cd);
log('Dd', Dd);
log('Ed', Ed);
console.log('from timestamp:', ts)
log('At', At);
log('Ct', Ct);
log('Dt', Dt);
function parseDate(dateStr) {
let [year,month,day] = dateStr.split(' ')[0].split('-');
let d=new Date(0);
d.setUTCFullYear(year);
d.setUTCMonth(month-1);
d.setUTCDate(day)
return d;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment-with-locales.min.js"></script>
This snippet only presents used soultions
Results for chrome
Convert to format pt-BR:
var dateString = "13/10/2014";
var dataSplit = dateString.split('/');
var dateConverted;
if (dataSplit[2].split(" ").length > 1) {
var hora = dataSplit[2].split(" ")[1].split(':');
dataSplit[2] = dataSplit[2].split(" ")[0];
dateConverted = new Date(dataSplit[2], dataSplit[1]-1, dataSplit[0], hora[0], hora[1]);
} else {
dateConverted = new Date(dataSplit[2], dataSplit[1] - 1, dataSplit[0]);
}
I hope help somebody!!!
I have created a fiddle for this, you can use toDate() function on any date string and provide the date format. This will return you a Date object.
https://jsfiddle.net/Sushil231088/q56yd0rp/
"17/9/2014".toDate("dd/MM/yyyy", "/")
For сonverting string to date in js i use http://momentjs.com/
moment().format('MMMM Do YYYY, h:mm:ss a'); // August 16th 2015, 4:17:24 pm
moment().format('dddd'); // Sunday
moment().format("MMM Do YY"); // Aug 16th 15
moment().format('YYYY [escaped] YYYY'); // 2015 escaped 2015
moment("20111031", "YYYYMMDD").fromNow(); // 4 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 3 years ago
moment().startOf('day').fromNow(); // 16 hours ago
moment().endOf('day').fromNow(); // in 8 hours
I made this function to convert any Date object to a UTC Date object.
function dateToUTC(date) {
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}
dateToUTC(new Date());
You Can try this:
function formatDate(userDOB) {
const dob = new Date(userDOB);
const monthNames = [
'January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December'
];
const day = dob.getDate();
const monthIndex = dob.getMonth();
const year = dob.getFullYear();
// return day + ' ' + monthNames[monthIndex] + ' ' + year;
return `${day} ${monthNames[monthIndex]} ${year}`;
}
console.log(formatDate('1982-08-10'));
This answer is based on Kassem's answer but it also handles two-digit years. I submitted an edit to Kassem's answer, but in case it wasn't approved, I'm also submitting this as a separate answer.
function stringToDate(_date,_format,_delimiter) {
var formatLowerCase=_format.toLowerCase();
var formatItems=formatLowerCase.split(_delimiter);
var dateItems=_date.split(_delimiter);
var monthIndex=formatItems.indexOf("mm");
var dayIndex=formatItems.indexOf("dd");
var yearIndex=formatItems.indexOf("yyyy");
var year = parseInt(dateItems[yearIndex]);
// adjust for 2 digit year
if (year < 100) { year += 2000; }
var month=parseInt(dateItems[monthIndex]);
month-=1;
var formatedDate = new Date(year,month,dateItems[dayIndex]);
return formatedDate;
}
stringToDate("17/9/14","dd/MM/yyyy","/");
stringToDate("17/9/2014","dd/MM/yyyy","/");
stringToDate("9/17/2014","mm/dd/yyyy","/")
stringToDate("9-17-2014","mm-dd-yyyy","-")
var date = new Date(year, month, day);
or
var date = new Date('01/01/1970');
date string in format '01-01-1970' will not work in FireFox, So better use "/" instead of "-" in date format string.
Yet another way to do it:
String.prototype.toDate = function(format) {
format = format || "dmy";
var separator = this.match(/[^0-9]/)[0];
var components = this.split(separator);
var day, month, year;
for (var key in format) {
var fmt_value = format[key];
var value = components[key];
switch (fmt_value) {
case "d":
day = parseInt(value);
break;
case "m":
month = parseInt(value)-1;
break;
case "y":
year = parseInt(value);
}
}
return new Date(year, month, day);
};
a = "3/2/2017";
console.log(a.toDate("dmy"));
// Date 2017-02-03T00:00:00.000Z
You can using regex to parse string to detail time then create date or any return format like :
//example : let dateString = "2018-08-17 01:02:03.4"
function strToDate(dateString){
let reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}).(\d{1})/
, [,year, month, day, hours, minutes, seconds, miliseconds] = reggie.exec(dateString)
, dateObject = new Date(year, month-1, day, hours, minutes, seconds, miliseconds);
return dateObject;
}
alert(strToDate(dateString));
If you need to check the contents of the string before converting to Date format:
// Convert 'M/D/YY' to Date()
mdyToDate = function(mdy) {
var d = mdy.split(/[\/\-\.]/, 3);
if (d.length != 3) return null;
// Check if date is valid
var mon = parseInt(d[0]),
day = parseInt(d[1]),
year= parseInt(d[2]);
if (d[2].length == 2) year += 2000;
if (day <= 31 && mon <= 12 && year >= 2015)
return new Date(year, mon - 1, day);
return null;
}
I have created parseDateTime function to convert the string to date object and it is working in all browser (including IE browser), check if anyone required, reference
https://github.com/Umesh-Markande/Parse-String-to-Date-in-all-browser
function parseDateTime(datetime) {
var monthNames = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
if(datetime.split(' ').length == 3){
var date = datetime.split(' ')[0];
var time = datetime.split(' ')[1].replace('.00','');
var timearray = time.split(':');
var hours = parseInt(time.split(':')[0]);
var format = datetime.split(' ')[2];
var bits = date.split(/\D/);
date = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
if ((format === 'PM' || format === 'pm') && hours !== 12) {
hours += 12;
try{ time = hours+':'+timearray[1]+':'+timearray[2] }catch(e){ time = hours+':'+timearray[1] }
}
var formateddatetime = new Date(monthNames[monthIndex] + ' ' + day + ' ' + year + ' ' + time);
return formateddatetime;
}else if(datetime.split(' ').length == 2){
var date = datetime.split(' ')[0];
var time = datetime.split(' ')[1];
var bits = date.split(/\D/);
var datetimevalue = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
var day = datetimevalue.getDate();
var monthIndex = datetimevalue.getMonth();
var year = datetimevalue.getFullYear();
var formateddatetime = new Date(monthNames[monthIndex] + ' ' + day + ' ' + year + ' ' + time);
return formateddatetime;
}else if(datetime != ''){
var bits = datetime.split(/\D/);
var date = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
return date;
}
return datetime;
}
var date1 = '2018-05-14 05:04:22 AM'; // yyyy-mm-dd hh:mm:ss A
var date2 = '2018/05/14 05:04:22 AM'; // yyyy/mm/dd hh:mm:ss A
var date3 = '2018/05/04'; // yyyy/mm/dd
var date4 = '2018-05-04'; // yyyy-mm-dd
var date5 = '2018-05-14 15:04:22'; // yyyy-mm-dd HH:mm:ss
var date6 = '2018/05/14 14:04:22'; // yyyy/mm/dd HH:mm:ss
console.log(parseDateTime(date1))
console.log(parseDateTime(date2))
console.log(parseDateTime(date3))
console.log(parseDateTime(date4))
console.log(parseDateTime(date5))
console.log(parseDateTime(date6))
**Output---**
Mon May 14 2018 05:04:22 GMT+0530 (India Standard Time)
Mon May 14 2018 05:04:22 GMT+0530 (India Standard Time)
Fri May 04 2018 00:00:00 GMT+0530 (India Standard Time)
Fri May 04 2018 00:00:00 GMT+0530 (India Standard Time)
Mon May 14 2018 15:04:22 GMT+0530 (India Standard Time)
Mon May 14 2018 14:04:22 GMT+0530 (India Standard Time)
ISO 8601-esque datestrings, as excellent as the standard is, are still not widely supported.
This is a great resource to figure out which datestring format you should use:
http://dygraphs.com/date-formats.html
Yes, that means that your datestring could be as simple as as opposed to
"2014/10/13 23:57:52"
instead of
"2014-10-13 23:57:52"
//little bit of code for Converting dates
var dat1 = document.getElementById('inputDate').value;
var date1 = new Date(dat1)//converts string to date object
alert(date1);
var dat2 = document.getElementById('inputFinishDate').value;
var date2 = new Date(dat2)
alert(date2);
use this code : (my problem was solved with this code)
function dateDiff(date1, date2){
var diff = {} // Initialisation du retour
var tmp = date2 - date1;
tmp = Math.floor(tmp/1000); // Nombre de secondes entre les 2 dates
diff.sec = tmp % 60; // Extraction du nombre de secondes
tmp = Math.floor((tmp-diff.sec)/60); // Nombre de minutes (partie entière)
diff.min = tmp % 60; // Extraction du nombre de minutes
tmp = Math.floor((tmp-diff.min)/60); // Nombre d'heures (entières)
diff.hour = tmp % 24; // Extraction du nombre d'heures
tmp = Math.floor((tmp-diff.hour)/24); // Nombre de jours restants
diff.day = tmp;
return diff;
}
I wrote a reusable function that i use when i get date strings from the server.
you can pass your desired delimiter( / - etc..) that separates the day month and year in order to use the split() method.
you can see & test it on this working example.
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
<div>
<span>day:
</span>
<span id='day'>
</span>
</div>
<div>
<span>month:
</span>
<span id='month'>
</span>
</div>
<div>
<span>year:
</span>
<span id='year'>
</span>
</div>
<br/>
<input type="button" id="" value="convert" onClick="convert('/','28/10/1980')"/>
<span>28/10/1980
</span>
<script>
function convert(delimiter,dateString)
{
var splitted = dateString.split('/');
// create a new date from the splitted string
var myDate = new Date(splitted[2],splitted[1],splitted[0]);
// now you can access the Date and use its methods
document.getElementById('day').innerHTML = myDate.getDate();
document.getElementById('month').innerHTML = myDate.getMonth();
document.getElementById('year').innerHTML = myDate.getFullYear();
}
</script>
</body>
</html>

how to display the date as a day/month/year format after adding 10 days to current date

so I got this function that adds 5 days to the current date, the only problem is that the date is displayed as "Mon May 30 2022 00:16:04 GMT+0300 (Eastern European Summer Time)" I need a simple, clean format like 22/07/2002.
<div class="container-date">
<p>Offer expires on <span id="date"></span></p>
</div>
ar d = new Date();
d.setDate(d.getDate() + 10);
document.getElementById("date").innerHTML = d ;
SUGGESTION
You can use formatDate(date, timeZone, format) method to easily format date objects. See this quick sample below:
SCRIPT
function test() {
var d = new Date();
var formattedDate = Utilities.formatDate(new Date(d.setDate(d.getDate() + 5)), Session.getScriptTimeZone(), "dd/MM/yyyy")
console.log(formattedDate);
}
Demo:
date.toISOString().slice(0, 10): Convert date to string and get first 10 character.
toISOString() (2022-05-29T23:03:31.782Z to 2022-05-29)
date.split('-').reverse().join('/'): Split string by -, reverseit for formatting and convert array to a string with / separator. (2022-05-29 to 29/05/2022)
const addDays = (days) => {
let date = new Date();
date.setDate(date.getDate() + days);
date = date.toISOString().slice(0, 10);
return date.split('-').reverse().join('/');
}
const date = addDays(5);
console.log(date);
Format Date and add days to it
function formatDate(days = 10) {
const dt = new Date();
Logger.log(Utilities.formatDate(new Date(dt.getFullYear(),dt.getMonth(),dt.getDate() + days),Session.getScriptTimeZone(),"dd/MM/yyyy"));
}
Execution log
5:11:55 PM Notice Execution started
5:11:54 PM Info 03/06/2022
5:11:56 PM Notice Execution completed
Try this
// Note this wont calculate 5days ahead ,it just gives the asked format!
var today = new Date();
var dd = String(today.getDate()).padStart(2,'0');
to the current date
var mm = String(today.getMonth()+1).padStart(2,'0');
var yyyy = today.getFullYear();
today = dd + '/' + mm + '/' + yyyy;
console.log(today);
This should work if the days overflow with the months.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Add Days to Date</title>
</head>
<body>
<div class="container-date">
<p>Offer expires on <span id="date"></span></p>
</div>
<script>
//Date class
var d = new Date();
//Returns the current day
var day = d.getDate();
//Returns the current month
var month = d.getMonth();
//Returns the current year
var year = d.getFullYear();
//New Date Class for the current date plus added days
//Days overflowing will make a new month and a new year if needed
//see "https://www.w3schools.com/js/js_dates.asp" for more info
var newDate = new Date(year, month, day+5);
//month indexes are 0-11 for Jan-Dec, so the added one is necessary
var dd = newDate.getDate();
var mm = newDate.getMonth()+1;
var yyyy = newDate.getFullYear();
//for the double digit string
dd = dd.toString().padStart(2,"0");
mm = mm.toString().padStart(2,"0");
//Date string Message
var dateString = `${dd}/${mm}/${yyyy}`;
document.getElementById("date").innerHTML = dateString;
</script>
</body>
</html>

Date calculation using javaScript

I need date algorithms, Which will display me how long I have been given a date anywhere.
Example:
Suppose
Today is 01/06/2019 (dd/mm/yy)
BirthDate is 31/05/2019 (dd/mm/yy)
Now, My age is 1 day 0 Months and 0 years
[NOTE: I need all of them, It means day/month and years]
I have been read at least 23 articles/post in this site but they only give years or month or date but not everything in one...
var date, cDate, cMonth, cYears, oDate, oMonth, oYears;
date = new Date()
//current date
cDate = date.getDate()
cMonth = date.getMonth()
cYears = date.getFullYear()
//birth date
oDate = 01
oMonth = 05
oYears = 2019
(Multiplying is not the main solution I think so, need to work with all arithmetics operator)
This will give you the result you need
var birth = new Date("5/31/2019"); // mm/dd/year
var today = new Date();
var diff = today.valueOf()-birth.valueOf();
var result = new Date(diff);
var dayDiff = result.getDate() - 1; //because epoch start from 1st
var yearDiff = result.getFullYear() - 1970; //because epoch start from 1970
var str = `${dayDiff} day ${result.getMonth()} Months and ${yearDiff} years`;
console.log(str);
You should use moment, so there you can do:
var a = moment("04/09/2019 15:00:00");
var b = moment("04/09/2013 14:20:30");
console.log(a.diff(b, 'years'))
console.log(a.diff(b, 'months'))
console.log(a.diff(b, 'days'))
Similarly, you can get minutes, hours and seconds if you need.
While using the library moment.js

Javascript: formatting a date [duplicate]

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 4 years ago.
I want to the current date/time formatted in this format:
year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second+':'+milli;
Currently I'm doing it as such. Is there a more elegant approach without the use of external libraries like moment.js?
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var milli = now.getMilliseconds();
if(month.toString().length == 1) {
var month = '0'+month;
}
if(day.toString().length == 1) {
var day = '0'+day;
}
if(hour.toString().length == 1) {
var hour = '0'+hour;
}
if(minute.toString().length == 1) {
var minute = '0'+minute;
}
if(second.toString().length == 1) {
var second = '0'+second;
}
if(milli.toString().length == 1) {
var milli = '0'+milli;
}
var m_session_startTime = year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second+':'+milli;
Leverage template literals instead of concatenation and padStart() to fill leading zeros.
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, "0");
const day = String(now.getDate()).padStart(2, "0");
const hour = String(now.getHours()).padStart(2, "0");
const minute = String(now.getMinutes()).padStart(2, "0");
const second = String(now.getSeconds()).padStart(2, "0");
const milli = String(now.getMilliseconds()).padStart(4, "0");
const m_session_startTime = `${year}-${month}-${day} ${hour}:${minute}:${second}:${milli}`;
console.log(m_session_startTime);
You could use moment.js, it really helps you with formatting dates.
console.log(moment().format('YYYY-MMMM-DD h:mm:ss:SSS'));
<script src="https://momentjs.com/downloads/moment.min.js"></script>
This command does the job pretty well. moment() is a date object, when there are no arguments given like in this example it takes the current time but you can also use moment("2018-12-4") for specific dates.
You can then format the date according to your need,
YYYY is the full year (2018)
MMMM is the full month name (July)
(you can also use MMM for the short version of the month name)
DD is the day as a number (24)
(you can also use dddd for the full name of the day or ddd for the short name)
h is the hour as number (22)
mm is the minute as a number (23)
ss is the second as a number (as an example 22)
SSS is the millisecond as a number (example 245)
Try this?
let date = new Date();
let jsonDate = date.toJSON();
jsonDate = jsonDate.replace(/[TZ]/g, " ");
jsonDate = jsonDate.replace(/\./g, ":");
console.log(jsonDate);
> 2018-07-24 20:32:06:435
Alternatively, if you want to split the entire thing into substrings:
let date = new Date();
let jsonDate = date.toJSON();
jsonDate = jsonDate.replace(/[TZ]/g, " ");
jsonDate = jsonDate.replace(/\./g, ":");
let dateTime = jsonDate.split(" ");
let dt = dateTime[0].split("-");
let tt = dateTime[1].split(":");
let year = dt[0];
let month = dt[1];
let day = dt[2];
let hour = tt[0];
let minute = tt[1];
let second = tt[2];
let mili = tt[3];
console.log(jsonDate);
console.log(dateTime[0]);
console.log(dateTime[1]);
console.log([year, month, day, hour, minute, second, mili].join("~"));
console.log("Date: " + [year, month, day].join("-") + " Time: " + [hour, minute, second, mili].join(":"));
> 2018-07-24 21:03:05:706
> 2018-07-24
> 21:03:05:706
> 2018~07~24~21~03~05~706
> Date: 2018-07-24 Time: 21:03:05:706
As you might have noticed from this response, I work with databases. I have heavy bash, javascript, php, sql, golang background.
Use a moment.js. Great library that is designed to exactly what you would like. You can use the .format option.
var now = moment().format('YYYY-MM-DD HH:mm:ss.SSS');
$('#timeval').text(now);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Current Time: <br>
<a id="timeval"></a>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
https://momentjs.com/

Last 7 days javascript

I have a report create time as 2016-05-30, now I need to get the last 7 days from the report time.How can I get using moment?
report_create_time = moment('2016-05-30').format('MMM DD, YYYY');
I see this but it gives 7 days from the current date but I want from the report_Create_time.
dateFrom = moment().subtract(7,'d').format('YYYY-MM-DD');
you can try this pure javascript
var d = new Date('2016-05-30');
var day = d.getDate() - 7;
var month = d.getMonth();
var year = d.getFullYear();
var d1 = new Date(year+"-"+month+"-"+day);
alert(d1);
https://jsfiddle.net/c6c2vur8/
Small change needed
report_create_time = moment('2016-05-30');
dateFrom = report_create_time.subtract(7,'days');
report_create_time = report_create_time.format('MMM DD, YYYY'); // if you needed this formatted date to show in your HTML
dateFrom is the day before 7 days. so we need days from dateFrom to report_create_time
If you have both the dates, you can add 1 day from dateFrom up to seven days
var dates = []
for(var i=1; i<=7; i++){
dates[i-1] = dateFrom.add('1', 'days').fotmat('MMM DD, YYYY')
}
If you don't need this way, you can subtract 1 day from report_create_time 7 times

Categories