How to deduct time in 24 hours using moment - javascript

My use case is very simple, How do i deduct the current time in 24 hours. Technically it is like snapchat, 24 hours from now it will dissapear, hence why I need to deduct the time.
11:50 PM - 10 Jan 2017
I want to deduct the current time to the next 24 hours time only
(10:50 PM - 11 Jan 2017) - (11:50 PM 10 Jan 2017) = 1 hour left
How would I do such thing in Moment.js ?

You can add -24 hours. See moment.add
moment(date).add(-24, 'hours');
And to display relative time you can use moment.fromNow

I think this would help you :
//valid formats to subtract
moment().subtract(String, Number);
moment().subtract(Number, String); // 2.0.0
moment().subtract(String, String); // 2.7.0
moment().subtract(Duration); // 1.6.0
moment().subtract(Object);
//easy examples
var myString = "03:15:00",
myStringParts = myString.split(':'),
hourDelta: +myStringParts[0],
minuteDelta: +myStringParts[1];
date.subtract({ hours: hourDelta, minutes: minuteDelta});
date.toString()

Read http://momentjs.com/docs/#/parsing/ for documentation on moment js parse.
This just might work. It did work in JSFiddle http://jsfiddle.net/Bjolja/p2bcm2oa/
var dt = moment("12:15 AM", ["h:mm A"]).format("HH:mm");

Yes you should use moment.js take a look here
Moment from method
In fact you can deduct time passed between to dates like this
var start = moment("10:50 PM - 11 Jan 2017");
var end = moment("11:50 PM 10 Jan 2017");
start.from(end); // "1 hour"

Related

Why .getMinutes() output as :0 instead of :00 in JavaScript?

The .getMinutes() method only outputs one integer ‘0’ instead of two integers ‘00’. Why does it do this and is there a simpler way to fix this?
Example:
var dateDue = new Date("Fri Apr 22 2022 18:00:00");
dateDue.getMinutes(); //Expected output: 18:00, got 18:0 instead?
For now I have been using if statement validation to add 0 whenever the minutes .Length returns as only being one character long instead of two.
//Minutes display validation for dateDue
var minutesDue = dateDue.getMinutes();
if (minutesDue.Length === 1) {
minutesDue = parseInt(dateDue.getMinutes()) + "0";
Coding language: JavaScript (vanilla)
Skill level: Beginner
Editor: Visual Studio Code
OS: Windows 7
You can use the toLocaleTimeString method with some options for padding and even more styling. This one does AM/PM automatically for you.
const time = new Date("Fri Apr 22 2022 18:00:00").toLocaleTimeString('default', { hour: '2-digit', minute: '2-digit' });
console.log(time) // '06:00 PM'
I could answer half the question if it helps to start thinking process. To put :00 for seconds. You need a loop which checks the condition, if seconds less than 9. If that's the case concatenate 0 to secs.
var dateDue = new Date("Fri Apr 22 2022 18:00:00");
if (dateDue.getMinutes() < 10) {
var getMinutes= '0' + dateDue.getMinutes();
}

weird seconds offset in js date object in chrome

When looking at the valueOf value of a date object at the beggining of a year i expected to always receive zero seconds.
The following code shows that until 1917 there was an offset of 54 seconds or 40 seconds in chrome. in IE i receive 0 seconds for all years.
Is there a reason for this? it seems to only happen in the last chrome version
for(var i=0; i<2020;i++)
if(!new Date(i,0,1).valueOf().toString().match("00000$"))
console.log({
y:i,
s: new Date(i,0,1).valueOf().toString().match(/(\d{2})\d{3}$/)[1]})
This is Not a BUG..
As #Krzysztof pointed out Chrome has implemented a new spec for timezone offset calculation following the merge of Make LocalTZA take 't' and 'isUTC' and drop DSTA(t) to Ecma 262. So now the time-zone conversion does not work by just backward interval of seconds, it is calculated as what local time was being observed in a specific region.
Explanation:
I am from a wonderful little country called Bangladesh of South-Asia which follows BST(Bangladesh Standard Time +0600 GMT), which was not always exactly 6 hours ahead of GMT. As JavaScript date takes in local time when I print the start time of this year in GMT I get:
new Date(2018, 0, 1).toUTCString()
// "Sun, 31 Dec 2017 18:00:00 GMT"
In 2009 one hour day-light saving was observed in Bangladesh from 19 June to 31 December. So if I print the first day of December 2009 I get:
new Date(2009, 11, 1).toUTCString()
// "Mon, 30 Nov 2009 17:00:00 GMT"
You can see the day-light saving is now reflected in the date now, which is not visible in my nodeJS console. There was also changes in local time in 1941-1942 as shown below and can be seen on timeanddate.com:
All of the changes are reflected in Chrome now:
new Date(1941, 6, 1).toUTCString()
// "Mon, 30 Jun 1941 18:06:40 GMT"
new Date(1941, 11, 1).toUTCString()
// "Sun, 30 Nov 1941 17:30:00 GMT"
new Date(1942, 7, 1).toUTCString()
// "Fri, 31 Jul 1942 18:30:00 GMT"
new Date(1942, 11, 1).toUTCString()
// "Mon, 30 Nov 1942 17:30:00 GMT"
So now if I pick any date before 1941 keeping in mind my local time is 6 hours ahead I see an offset of 6 minutes 40 seconds. It will vary depending on the time-zone for the back dates due to the recent update of Chrome, or specifically saying the update of ECMAScript(JavaScript).
This may not be 100% the solution of the problem, but one can get the "jitter" introduced by chrome by casting it to UTC and back, then compensate with a new new Date(oldDate.getTime() + jitter).
// Compensates for google chrome 67+ issue with very old dates.
// We should skip this test if any other browser.
$getJitter: function (d) {
var utcDate = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCMilliseconds())),
jitter = 0;
// As we're setting UTC date, the non-UTC year could be
// shifted one ahead or behind, so set the utc full
// year to ensure compliance.
utcDate.setUTCFullYear(d.getUTCFullYear());
if (d.getFullYear() != utcDate.getFullYear() ||
d.getMonth() != utcDate.getMonth() ||
d.getDate() != utcDate.getDate() ||
d.getHours() != utcDate.getHours() ||
d.getMinutes() != utcDate.getMinutes() ||
d.getMilliseconds() != utcDate.getMilliseconds()) {
// infers the "jitter" introduced during the conversion to compensate in the
// actual value of ticks
jitter = d.getTime() - utcDate.getTime()
}
return jitter;
}
This "jitter" pretty much depends on the time zone. For Brazil I'm getting a 28 seconds noise (so it gets back to like, 12:00:00 AM > 23:59:32 PM the previous day.
For Brazil the issue happens down to 1913. This coincides with the time we got our daylight saving times and time zone to -3:00 from -3:06, according to the time changes over years at https://www.timeanddate.com/time/zone/brazil/sao-paulo.
With the above code you can explore the broken dates with this loop:
for (var i=1900; i < 2020; i++) {
for (var j=0; j < 12; j++) {
var dt = new Date(i, j, 1);
var jitter = System.DateTime.$getJitter(dt);
if (jitter != 0) {
console.log("broken: " + i + ", " + j + ", jitter: " + (jitter/1000) + "s: " + dt.toString());
}
}
}

get week number from date in whole week base in javascript

I have searched the web and found the script to get the week number in year. However my counting is difference. The below image is the week number I want to get. When I tested using '1/5/2015', my code got week number is 2, but the week number should be 1 in my requirement. Would someone can help me. Thanks in advance.
I found the javascript at IamSilviu/Get week number
There is my code:
function myWeekNumber(thisDate) {
var dt = new Date(thisDate)
var onejan=new Date(dt.getFullYear(), 0, 2);
return Math.ceil((((dt - onejan) / 86400000) + onejan.getDay() + 1) / 7); }
The algorithm you're trying to implement seems to be that:
Weeks start on Sunday
The first week of the year is the one that has any days in the year, e.g. 1 Jan 2016 was a Friday, so the first week of 2016 started on Sunday 27 December 2015
In this case, it's best to use UTC methods to avoid daylight saving issues:
function getWeekNumberNonISO(d) {
// Create UTC equivalent for 23:59:59.999 on the passed in date
var sat = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(),23,59,59,999));
// Set to Saturday at end of week
sat.setUTCDate(sat.getUTCDate() + 6 - sat.getUTCDay());
// Get first day of year
var firstDay = new Date(Date.UTC(sat.getUTCFullYear(), 0, 1));
// Set to Sunday on or before, i.e. first day of first week in year
firstDay = firstDay.setUTCDate(firstDay.getUTCDate() - firstDay.getUTCDay());
// Week number is difference in dates divided by ms/week rounded
return Math.round((sat - firstDay)/(6.048e8));
}
// Get week number for Mon 5 Jan 2015
console.log(getWeekNumberNonISO(new Date(2015,0,5))); // 2
// Get week number for Sat 31 Dec 2011
console.log(getWeekNumberNonISO(new Date(2011,11,31))); //53
// Get week number for Sat 1 Jan 2011
console.log(getWeekNumberNonISO(new Date(2011,0,1))); // 1
// Get week number for Sun 2 Jan 2011
console.log(getWeekNumberNonISO(new Date(2011,0,2))); // 2
Js has function inbulid function which can be used to fetch the date from the given date of the week getweek().
var week=date.getWeek()

JavaScript Dateobject Increment goes wrong

I want to increment the year-value of a given date, but this goes wrong.
this is my code:
var endDate = entry.start;
endDate.setDate(endDate.getFullYear() + 5);
and for comparison the output (console.log) is:
Date {Thu Jun 30 2011 11:30:10 GMT+0200}
Date {Tue Dec 06 2016 11:30:10 GMT+0100}
as you can see, it also incremented the month and Day.
What am I missing?
thanks in advance
You have to set the year only, using the setYear method:
endDate.setYear(endDate.getFullYear() + 5);
Using setDate(getFullYear()+5) you add 5 + (year of the date) days to the date value of endDate
You're adding 2016 days to it, not modifying the year, which is 5 and a half year.

Problem in adding days / month / year to a given date using javascript?

I trying to add days / months / year to a given date and map it to an input field
var d = new Date();
d.setDate(15);
d.setMonth(06);
d.setYear(2011);
document.getElementById("test").innerHTML=d;
d.setDate(d.getDate()+20);
document.getElementById("test").innerHTML+=""+d.getDate()+"/"+d.getMonth()+"/"+d.getYear("YY");
this actually prints out
Fri Jul 15 2011 12:45:48 GMT+0530 (India Standard Time)
4/7/111
actually this is wrong.. it should print out 5/7/2011.. i think by default the system takes as "30" days for a month and adds the +20 days.. but actually Jun has 30 days so that result should be 5/7/2011..
any suggestion about what goes wrong in here.. any alternative for this?
At the first, you have better to use getFullYear to get year as 2011. You did get number from getDate() and add 20. This break Date. You should get long value from getTime(), and add milli-seconds.
<div id="test"></div>
<script>
var d = new Date();
d.setDate(15);
d.setMonth(06);
d.setFullYear(2011);
document.getElementById("test").innerHTML+=" "+d.getDate()+"/"+d.getMonth()+"/"+d.getFullYear();
d.setTime(d.getTime()+1000*60*60*24*20);
document.getElementById("test").innerHTML+=" "+d.getDate()+"/"+d.getMonth()+"/"+d.getFullYear();
</script>
> var d = new Date();
> d.setDate(15);
> d.setMonth(06);
> d.setYear(2011);
is equivalent to:
var d = new Date(2011,6,15); // 15 Jul 2011
Months are zero based (January = 0, December = 11).
Date.prototype.getYear is specified in ECMA-262 ed5 as Return YearFromTime(LocalTime(t)) − 1900. so:
alert(d.getYear()); // 111
whereas:
alert(d.getFullYear()); // 2011
i think by default the system takes as "30" days for a month and adds the +20 days.. but actually May has 31 days so that result should be 5/7/2011.
You are interpreting it a wrong way, Month in a date starts with 0 - Jan..
So as per the date entered by you it comes Jul 15 2011 on the month number 6.
When you add 20 to date it will be Aug 04 2011 and you are directly getting month number which is 7 - i.e. Aug which misleads your calculation. And for the year, yes it is you should getFullYear
Read this to get your basics correct..

Categories

Resources