Javascript - Format date to yyyy-mm-dd from unixtime - javascript

I need some help with converting unixtime to a specific format. Here is what I am currently working with:
var date = "2014-05-01";
var indexPie = Date.parse(date);
I need indexPie in yyyy-mm-dd format. What I do not understand is that when log
var newDate = new Date(indexPie);
The results is:
Wed Apr 30 2014 18:00:00 GMT-0600 (Mountain Daylight Time)
when it should be:
Thur May 01 2014 18:00:00 GMT-0600 (Mountain Daylight Time)
Why is new Date(indexPie) resulting in Apr 30 and how do I get my correct format of yyyy-mm-dd?
Any suggestions would be great. Thanks.

I resolved the issue with the following:
var date = new Date(indexPie);
var year = date.getUTCFullYear();
var month = date.getUTCMonth() + 1;
var day = date.getUTCDate();
var dateString = year + "-" + month + "-" + day;

You are expecting that the value in date variable: "2014-05-01" will be parsed as in local timezone, but actually it is parsed as in UTC.
You can convert the date from UTC to local timezone like this:
var newDate = new Date(indexPie + new Date().getTimezoneOffset() * 60000);

Related

Adding 30 days to the converted date is giving me Invalid Date message in browser's console log

I have converted the timestamp 4/1/2021 00:00 into the format Thu Apr 01 2021 00:00:00 GMT-0500 (Central Daylight Time) as shown in the code below. However, adding 30 days is not giving me appropriate result.
//Handling Date String: 4/1/2021 00:00
function setStart(input) {
if (!(input instanceof Date))
console.log('Handling Date String:' +input)
input = new Date(Date.parse(input));
input.setHours(0);
input.setMinutes(0);
input.setSeconds(0);
input.setMilliseconds(0);
start = input;
return start;
}
var initialDate = setStart('4/1/2021 00:00');
console.log("Printing converted date below:");
console.log(setStart('4/1/2021 00:00'));
var date = new Date(); // Now
//date.setDate(date.getDate() + 30); // Set now + 30 days as the new date
date.setDate(initialDate + 30);
console.log("Printing date after adding 30 days below")
console.log(date);
/* var getDaysArray = function(start, end) {
for(var arr=[],dt=new Date(start); dt<=new Date(end); dt.setDate(dt.getDate()+1)){
arr.push(new Date(dt));
}
return arr;
};
var daylist = getDaysArray(new Date("2018-05-01"),new Date("2018-06-01"));
console.log(daylist); */
The browser's console is printing it like the following:
Handling Date String:4/1/2021 00:00
Printing converted date below:
Handling Date String:4/1/2021 00:00
Thu Apr 01 2021 00:00:00 GMT-0500 (Central Daylight Time)
Printing date after adding 30 days below
Invalid Date
What is causing it to print Invalid Date ?
You want to get the date after 30 days from the initialDate, don't you?
refer this
var date = new Date(initialDate); // Now
//date.setDate(date.getDate() + 30); // Set now + 30 days as the new date
date.setDate(date.getDate() + 30);
console.log("Printing date after adding 30 days below")
console.log(date);
You should something like
var date = new Date().getTime(); // Now
const offset = 30*23*3600*1000;
const newDate = new Date(date+offset).toLocaleString('en-US', {timeZone: 'CST'}); // Change added
console.log("Printing date after adding 30 days below")
console.log(newDate);

How to get total minutes of difference between two dates using pure JavaScript

Updated My Question
How to get total minutes of difference between two dates using pure JavaScript when
Condition (1):: Same month, same year but date changes
newDate: 18/10/2016 0:50
oldDate: 17/10/2016 23:05
Condition (2):: Last date of current month and 1st date of next month
newDate: 1/11/2016 0:50
oldDate: 31/10/2016 23:05
Condition (3):: Last date of year and 1st date of new year
newDate: 1/1/2017 0:50
oldDate: 31/12/2016 23:05
Note: Please have a look newDate and oldDate to understand the conditions.
Thanks
Since you don't want to use a library for parsing date strings, you can write a simple function such as:
// Parse date string in "Sat Dec 31 2016 15:35:57 GMT+0530 (India Standard Time)" format
function parseDate(s) {
// Split into tokens
var b = s.match(/\w+/g) || [];
var months = 'jan feb mar apr may jun jul aug sep oct nov dec'.split(' ');
// Determine offset in minutes
var offSign = /GMT+/.test(s)? -1 : 1;
var offset = b[8].substr(0,2)*60 + +b[8].substr(2,2);
// Create date, applying offset to minutes
var date = new Date(Date.UTC(b[3],
months.indexOf(b[1].toLowerCase()),
b[2],
b[4],
+b[5] + (offSign*offset),
b[6]));
return date;
}
var d = parseDate("Sat Dec 31 2016 15:35:57 GMT+0530 (India Standard Time)")
console.log('UTC: ' + d.toISOString() + '\n' +
'Local: ' + d.toLocaleString());
Completed My Requirements with the below pure JavaScript code
In my code starttime and endtime are
//var startTime = localStorage.getItem("starttime");
//var endTime = new Date();
Example Here.
var startTime = new Date("Sat Dec 31 2016 15:35:57 GMT+0530 (India Standard Time)");
var endTime = new Date("Sun Jan 1 2017 15:35:57 GMT+0530 (India Standard Time)");
var totalMiliseconds = endTime - startTime;
alert(totalMiliseconds);
//output:: 86400000
var totalSeconds = totalMiliseconds/1000;
alert(totalSeconds);
//output:: 86400
var totalMinuts = totalSeconds/60;
alert(totalMinuts);
//output:: 1440
var totalHours = totalMinuts/60;
alert(totalHours);
//output:: 24
And this fulfill my all 3 conditions.
Thank You For Your Support !!!

Javascript Date add days

var date = new Date();
var date2 = new Date();
daysinadvance = document.getElementById('AdvanceDays').value;
date2.setDate(date.getDate()+daysinadvance);
console.log(date2 + date + daysinadvance);
Fri Jan 28 2022 18:13:43 GMT+0000 (GMT Daylight Time)
Mon Apr 28 2014 18:13:43 GMT+0100 (GMT Standard Time)
60
If I pass in a directly typed number so + 60, it works fine but using the variable, I get a date in 2022. All I would like is the date2 to be current date + 60 days so I can update my validation.
Any help please?
Convert the value to a number first, e.g. with the unary plus operator:
var daysinadvance = +document.getElementById('AdvanceDays').value;
// ^ unary plus
Otherwise daysinadvance will be a string and you are doing string concatenation.

How To add number of month into the given date in javascript?

I want to add month into the select date by the user.
startdate=document.getElementById("jscal_field_coverstartdate").value;
now I want to add 11 month from the above startdate. How to do that.
date format = 2013-12-01
Without the date format it is difficult to tell, however you can try like this
add11Months = function (date) {
var splitDate = date.split("-");
var newDate = new Date(splitDate[0], splitDate[1] - 1, splitDate[2]);
newDate.setMonth(newDate.getMonth() + 11);
splitDate[2] = newDate.getDate();
splitDate[1] = newDate.getMonth() + 1;
splitDate[0] = newDate.getFullYear();
return startdate = splitDate.join("-");
}
var startdate = add11Months("2013-12-01");
alert(startdate)
JSFiddle
If your startdate is in correct date format you can try using moment.js or Date object in javascript.
In Javascript, it can be achieved as follow:
var date = new Date("2013-12-01");
console.log(date);
//output: Sun Dec 01 2013 05:30:00 GMT+0530 (India Standard Time)
var newdate = date.setDate(date.getDate()+(11*30));
console.log(new Date(newdate));
// output: Mon Oct 27 2014 05:30:00 GMT+0530 (India Standard Time)
In above lines, I have used 30 days per month as default. So you will get exact 11 month but little deviation in date. Is this what you want ? You can play around this likewise. I hope it help :)
For more about Date you can visit to MDN.
You can do it like this:
var noOfMonths = 11
var startdate = document.getElementById("jscal_field_coverstartdate").value;
startdate.setMonth(startdate.getMonth() + noOfMonths)
Try this:
baseDate.setMonth(2);
baseDate.setDate(30);
noMonths = 11;
var sum = new Date(new Date(baseDate.getTime()).setMonth(baseDate.getMonth() + noMonths);
if (sum.getDate() < baseDate.getDate()) { sum.setDate(0); }
var m = newDate.getDate();
var d = newDate.getMonth() + 1;
var yyyy = newDate.getFullYear();
return (yyyy+"-"+m+"-"+d);
Notes:
Adding months (like adding one month to January 31st) can overflow the days field and cause the month to increment (in this case you get a date in March). If you want to add months and then overflow the date then .setMonth(base_date.getMonth()+noMonths) works but that's rarely what people think of when they talk about incrementing months.
It handles cases where 29, 30 or 31 turned into 1, 2, or 3 by eliminating the overflow
Day of Month is NOT zero-indexed so .setDate(0) is last day of prior month.

Getting current time from the date object

function formatDate (input) {
var datePart = input.match(/\d+/g),
year = datePart[0].substring(2), // get only two digits
month = datePart[1], day = datePart[2];
document.write(new Date(day+'/'+month+'/'+year));
}
formatDate ('2010/01/18');
When i print this i get Thu Jun 01 1911 00:00:00 GMT+0530 (India Standard Time) but the system is actually 3:42 P.M
Use the current date to retrieve the time and include that in the new date. For example:
var now = new Date,
timenow = [now.getHours(),now.getMinutes(),now.getSeconds()].join(':'),
dat = new Date('2011/11/30 '+timenow);
you must give the time:
//Fri Nov 11 2011 00:00:00 GMT+0800 (中国标准时间)
alert(new Date("11/11/11"));
//Fri Nov 11 2011 23:23:00 GMT+0800 (中国标准时间)
alert(new Date("11/11/11 23:23"));
What do you want? Just the time? Or do you want to define a format? Cu's the code expects this format for date: dd/mm/yyyy, changed this to yyyy/mm/dd
Try this:
function formatDate (input) {
var datePart = input.match(/\d+/g),
year = datePart[0],
month = datePart[1], day = datePart[2],
now = new Date;
document.write(new Date(year+'/'+month+'/'+day+" " + now.getHours() +':'+now.getMinutes() +':'+now.getSeconds()));
}
formatDate ('2010/01/18')
Output:
Mon Jan 18 2010 11:26:21 GMT+0100
Passing a string to the Date constructor is unnecessarily complicated. Just pass the values in as follows:
new Date(parseInt(year, 10), parseInt(month, 10), parseInt(day, 10))
You're creating a Date() object with no time specified, so it's coming out as midnight. if you want to add the current date and time, create a new Date with no arguments and borrow the time from it:
var now = new Date();
var myDate = new Date(parseInt(year, 10), parseInt(month, 10), parseInt(day, 10),
now.getHours(), now.getMinutes(), now.getSeconds())
No need to strip the last two characters off the year. "2010" is a perfectly good year.

Categories

Resources