Javascript slice method not working as expected - javascript

I wrote a simple javascript function which converts string to date (in format 'dd.MM.yyyy HH.mm').
For extracting parts of that string, I've used slice method.
What is strange to me is that only day is returned as expected. All other variables are simply empty strings.
What am I doing wrong?
(
function(){
alert(GetDateFromStringDateTime("20.04.2017 18:15"));
}
)();
function GetDateFromStringDateTime(dateStr){
var day = dateStr.slice(0,2);
var month = dateStr.slice(3,2);
var year = dateStr.slice(6,4);
var hour = dateStr.slice(11,2);
var minute = dateStr.slice(14,2);
return new Date(year,month,day,hour,minute);
}
Picture from console window (month, year, hour and minute are empty strings):

String#slice() use a start and end parameter which are both zero-based index
console.log(GetDateFromStringDateTime("20.04.2017 18:15"));
function GetDateFromStringDateTime(dateStr) {
var day = dateStr.slice(0, 2);
var month = dateStr.slice(3, 5);
var year = dateStr.slice(6, 10);
var hour = dateStr.slice(11, 13);
var minute = dateStr.slice(14, 16);
console.log(day);
console.log(month);
console.log(year);
console.log(hour);
console.log(minute);
return new Date(year, month, day, hour, minute);
}

Use String.prototype.substr instead of slice

Related

Timestamp difference in seconds

I need difference of two timestamp in seconds. But when calculate it gave wrongly. How to calculate the seconds from difference of two timestamp? Thanks in advance.
Here,
First timestamp = 20180104113612
Second timestamp = 20180104113954
Difference = First timestamp - Second timestamp
It results as 342. But actually it should be 222. So please anyone help to find the difference in seconds?
You need to parse out year, month, day, hour, minutes and seconds from your date and create a date object and then subtract both dates to get the difference.
var firstTimestamp = 20180104113612,
secondTimestamp = 20180104113954,
getDate = (time) => {
time = time.toString();
var year = time.substring(0,4),
month = time.substring(4,6),
day = time.substring(6,8),
hour = time.substring(8,10),
minutes = time.substring(10,12),
seconds = time.substring(12,14);
return new Date(year, month, day, hour, minutes, seconds);
},
getTimeDifference = (firstTime, secondTime) => {
return Math.floor((getDate(secondTime) - getDate(firstTime))/1000);
};
console.log(getTimeDifference(firstTimestamp, secondTimestamp));
Try this
let startDate = new Date();
let endDate = new Date();
let differenceInSecond = (endDate - startDate) / 1000; //since it's originally in milliseconds
first you have to format your date in proper format something like this. "2018-01-04T11:36:12";
for formatting you can use make some function like this
function getFormat(dateString) {
var txt = dateString.slice(0, 4)
+ "-"
+ dateString.slice(4, 6)
+ "-"
+dateString.slice(6,8)
+"T"
+dateString.slice(8,10)
+":"
+dateString.slice(10,12)
+":"
+dateString.slice(12,14);
return txt;
}
and then convert it into javascript Date object.
const First_timestamp = 20180104113612;
const Second_timestamp = 20180104113954;
const FirstDate = new Date(getFormat(First_timestamp.toString()));
const SecondDate = new Date(getFormat(Second_timestamp.toString()));
const TimeDiffInSeconds = (SecondDate.getTime() - FirstDate.getTime()) / 1000;

TypeError: *.getMonth is not a function

I'm trying to build a javascript function that will auto-fill 14 days of a calendar with dates leading up to the last date, which is picked by a datepicker. So far my code is:
function filldates() {
datepicked = document.getElementById("period-ending").value;
s = datepicked.split('/');
enddate = new Date(s[2], s[0], s[1]);
date1 = enddate.setDate(enddate.getDate()-14);
day1 = date1.getMonth() + 1;
month1 = date1.getDate();
var firstday = day1 + '/' + month1;
document.getElementById("date-1").value = firstday;
}
However the developer's console keeps telling me that date1.getMonth is not a function. I'm confused because all of the tutorials and examples I've been looking at are based around something like: "var today = new Date(); var month = today.getMonth() + 1;"
Is this an implementation problem?
The setDate() function mutates its context date. It does not return a new Date instance.
If you want to create a new date instance that's some number of days ahead of another one:
function daysAfter(d, days) {
var nd = new Date(d.getTime());
nd.setDate(d.getDate() + days);
return nd;
}
Then if you've got a date, you can create a date 14 days after it like this:
var someDate = ... whatever ... ;
var fourteenDaysAfter = daysAfter(someDate, 14);
You can then use the .getMonth() and .getDate() accessors to do whatever formatting you want. Keep in mind that months are numbered from zero in JavaScript.
edit for dates before a date just pass a negative number.

Time between two times on current date

I am trying to calculate the time between two times on the current date using JavaScript. There are other questions similar to this one, but none seem to work, and few with many upvotes that I can find.
I have the following, which fails on the line: var diff = new Date(time1 - time2);, which always gives me an invalid Date when alerted, so it is clearly failing. I cannot work out why.
The initial date is added in the format of: hh:mm:ss in an input field. I am using jQuery.
$(function(){
$('#goTime').click(function(){
var currentDate = new Date();
var dateString = (strpad(currentDate.getDate()) +'-'+ strpad(currentDate.getMonth()+1)+'-'+currentDate.getFullYear()+' '+ $('#starttime').val());
var time1 = new Date(dateString).getTime();
var time2 = new Date().getTime();
var diff = new Date(time1 - time2);
var hours = diff.getHours();
var minutes = diff.getMinutes();
var seconds = diff.getMinutes();
alert(hours + ':' + minutes + ':' + seconds);
});
});
function strpad(val){
return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
}
dateString is equal to: 14-01-2013 23:00
You have the fields in dateString backwards. Swap the year and day fields...
> new Date('14-01-2013 23:00')
Invalid Date
> new Date('2013-01-14 23:00')
Mon Jan 14 2013 23:00:00 GMT-0800 (PST)
dd-MM-yyyy HH:mm is not recognized as a valid time format by new Date(). You have a few options though:
Use slashes instead of dashes: dd/MM/yyyy HH:mm date strings are correctly parsed.
Use ISO date strings: yyyy-MM-dd HH:mm are also recognized.
Build the Date object yourself.
For the second option, since you only really care about the time, you could just split the time string yourself and pass them to Date.setHours(h, m, s):
var timeParts = $('#starttime').val().split(':', 2);
var time1 = new Date();
time1.setHours(timeParts[0], timeParts[1]);
You are experiencing an invalid time in your datestring. time1 is NaN, and so diff will be. It might be better to use this:
var date = new Date();
var match = /^(\d+):(\d+):(\d+)$/.exec($('#starttime').val()); // enforcing format
if (!match)
return alert("Invalid input!"); // abort
date.setHours(parseInt(match[1], 10));
date.setMinutes(parseInt(match[2], 10));
date.setSeconds(parseInt(match[3], 10));
var diff = Date.now() - date;
If you are trying to calculate the time difference between two dates, then you do not need to create a new date object to do that.
var time1 = new Date(dateString).getTime();
var time2 = new Date().getTime();
var diff = time1 - time2;// number of milliseconds
var seconds = diff/1000;
var minutes = seconds/60;
var hours = minutes/60;
Edit: You will want to take into account broofa's answer as well to
make sure your date string is correctly formatted
The getTime function returns the number of milliseconds since Jan 1, 1970. So by subtracting the two values you are left with the number of milliseconds between each date object. If you were to pass that value into the Date constructor, the resulting date object would not be what you are expecting. see getTime

Convert Returned String (YYYYMMDD) to Date

I have a string that contains 8 digits that represent a date. For example:
20120515
I'd like to compare it with today's date, created in this manner:
var currentDate = new Date();
How can I convert the "8 digit date string" to a suitable date format in order to compare it to currentDate?
Use the substring method and substring off 4 elements and assign it to your new date for the year. Then substring off two elements at a time and store the month and date accordingly.
var dateString = "20120515";
var year = dateString.substring(0,4);
var month = dateString.substring(4,6);
var day = dateString.substring(6,8);
var date = new Date(year, month-1, day);
var currentDate = new Date();
Now you can compare the two dates with the normal operators.
If you want a small date library you can use moment.js.
var a = moment("20120515", "YYYYMMDD");
// then use any of moment's manipulation or display functionality
a.format("MMM Do YYYY"); // May 15th 2012
a.fromNow(); // 14 hours ago
a.calendar(); // Today at 12:00 AM
To correctly handle the local time zone, it must explicitly summed to the calculated time
function dateStringToDate(dateString) {
try {
var year = dateString.substring(0, 4);
var month = dateString.substring(4, 6);
var day = dateString.substring(6, 8);
var date = new Date(year, month - 1, day);
const offset = date.getTimezoneOffset()
date = new Date(date.getTime() - (offset * 60 * 1000));
return date;
} catch (error) {
return null;
}
}
function dateStringToDate(dateString) {
try {
var year = dateString.substring(0, 4);
var month = dateString.substring(4, 6);
var day = dateString.substring(6, 8);
var date = new Date(year, month - 1, day);
const offset = date.getTimezoneOffset()
date = new Date(date.getTime() - (offset * 60 * 1000));
return date;
} catch (error) {
return null;
}
}
console.log(dateStringToDate("20211212"))
console.log(dateStringToDate("20211213"))
console.log(dateStringToDate("20211214"))
...some other "one-liner" ways to accomplish this:
(They take a value like dts='20020704'; and return date object [dt].)
var dt=new Date(dts.slice(0,4), (dts[4]+dts[5])-1, dts[6]+dts[7]);
...or...
var m=dts.match(/(....)(..)(..)/), dt=new Date(m[1],m[2]-1,m[3]);
...or...
var m=dts.match(/.{1,2}/g), dt=new Date(m[0]+m[1],m[2]-1,m[3]);
The last one's shortest, but the first is probably most efficient, since it doesn't use regex (but that's irrelevant, unless you're processing LOTS of data using this). I like the middle one best since it's easy to see what's happening.

Get next date and day

I have a table to which i dynamically add rows. The number of days is equal to the date difference of the dates inserted by user. On the dynamic rows i want to add three fields. The first two are date and day filed. For that I need to know the next date and the corresponding day. For example user enters 10-2-2012. I need to insert The next dates like 17-2-2012,18-2-2012... and corresponding days like Wednesday, Thursday..etc
I have used the following function to get next date
function getTomorrow(d,offset)
{
if (!offset)
{
offset = 1
}
return new Date(new Date().setDate(d.getDate() + offset));
}
But it shows error 16-2-2012 has no getDate() function. Am not able to find next date and the corresponding day. Is there any way to get it?
You have to convert the string d into a Date object:
function getTomorrow(d,offset){
if (!offset){
offset = 1;
}
if(typeof(d) === "string"){
var t = d.split("-"); /* splits dd-mm-year */
d = new Date(t[2],t[1] - 1, t[0]);
// d = new Date(t[2],t[1] - 1, t[0] + 2000); /* for dd-mm-yy */
}
return new Date(d.setDate(d.getDate() + offset));
}
document.write(getTomorrow('16-02-2012',20) + ' test');
var k = getTomorrow('16-02-2012',1);
var myTime = k.getDate()+'-'+(k.getMonth()+1)+'-'+k.getFullYear();
alert(myTime);
JSFiddle Demo. See also http://www.w3schools.com/jsref/jsref_obj_date.asp.
var d=new Date();
d.setTime((d.getTime() + 86400 * 1000*1));
document.write(d);
document.write(d.getDay()+"-"+parseInt(d.getMonth()+1)+"-"+d.getFullYear());
if you need to know the date of day after tommorow , just change 1000*1 to 1000*2.
i giving a example
var year = 2010, month = 9, day = 14;
// The value of `meses`
var offset = 1; // Tomorow
var future_date = new Date(year, month , day+offset);
console.log(future_date);

Categories

Resources