javascript getTime() to 10 digits only - javascript

I am using the following function to get the Time using javascript:
function timeMil(){
var date = new Date();
var timeMil = date.getTime();
return timeMil;
}
And the value I get is:
1352162391299
While in PHP, I use the time(); function to get Time and the value I get is
1352162391
How do I convert the value of javascript time to remove the last 3 digits and make it 10 digits only.
From 1352162391299 To 1352162391
So that the Javascript time is the same with the PHP time.

I think you just have to divide it by 1000 milliseconds and you'll get time in seconds
Math.floor(date.getTime()/1000)

If brevity is ok, then:
function secondsSinceEpoch() {
return new Date/1000 | 0;
}
Where:
new Date is equivalent to new Date()
| 0 truncates the decimal part of the result and is equivalent to Math.floor(new Date/1000) (see What does |0 do in javascript).
Using newer features, and allowing for a Date to be passed to the function, the code can be reduced to:
let getSecondsSinceEpoch = (x = new Date) => x/1000 | 0;
But I prefer function declarations as I think they're clearer.

Try dividing it by 1000, and use parseInt method.
const t = parseInt(Date.now()/1000);
console.log(t);

function ts() {
return parseInt(Date.now()/1000);
}

You could divide by 1000 and use Math.floor() on JavaScript.

Related

Find the mid time value between two time values using momentjs

Assume I have two time values as startTime and endTime.
I want to find the exact mid value of this time objects.
Example: if startTime is 10:30 and endTime is 11:30, I need 11:00 as the midpoint value.
How to solve this using momentjs in JavaScript?
The middle between two dates is just half of the difference between the dates added to the smaller one.
The difference should be pretty straight forward:
Math.abs(moment(a).diff(b))
Math.abs() removes the minus from negative numbers (aka if a < b).
Calculating the middle has two steps too, first divide the difference by two, then add it to the smaller date (Math.min()):
diff/2+Math.min(moment(a).valueOf(),moment(b).valueOf())
moment(n).valueOf() turns your Date strings into comparable integers.
function middleDate(a,b) {
let diff = Math.abs(moment(a).diff(b))
let middle = diff/2+Math.min(moment(a).valueOf(),moment(b).valueOf())
return moment(middle)
}
console.log(middleDate("2022-01-27T10:30:00Z", "2022-01-27T11:30:00Z"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
If you only want the hours and minutes, you can just format the returned moment object (and use moment.utc() to remove the timezone):
function middleDate(a,b) {
let diff = Math.abs(moment(a).diff(b))
let middle = diff/2+Math.min(moment(a).valueOf(),moment(b).valueOf())
return moment(middle)
}
console.log(
moment.utc(middleDate("2022-01-27T10:30:00Z", "2022-01-27T11:30:00Z")).format("hh:mm")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Here is how i solved it
(For my particular case that deals with time only. For more generic cases, you can use the answer above)
import moment from 'moment';
export const middleDate = (startTime, endTime) => {
let duration = moment.duration(moment(endTime, 'HH:mm:ss').diff(moment(startTime, 'HH:mm:ss'))); //get Total Interval
let midInterval = duration.asHours() / 2; // find half of the interval
return moment(moment(startTime, 'HH:mm:ss')).add(midInterval, 'hour').format('HH:mm'); //add the mid interval to the startTime we have
};

How to make a time* range include upper bound

I've divided a day into 8 ticks of three hours each. When making this range it goes from 00:00 to 21:00, and not until 00:00 again.
const startDate = new Date("2021-03-14T23:00:00.000Z");
const endDate = new Date("2021-03-15T23:00:00.000Z");
const dayInThreeHourPeriods = d3.timeHour.every(3).range(startDate, endDate);
dayInThreeHourPeriods.forEach((period) => {
console.log(`period: ${format(period, 'HH:mm')}`);
});
// outputs
// from: 00:00
// to: 21:00
// would like it to go to 24:00
How can I change this so that it goes to 24:00?
I want to use it for an axis:
Made a working example here: https://jsfiddle.net/Spindle/kfL5oh12/21/
This is intended from the .range method, as d3.timeHour.every is just an alias to interval.range;
From d3-time docs:
interval.range(start, stop[, step]) · Source
Returns an array of dates representing every interval boundary after or equal to start (inclusive) and before stop (exclusive). If step is specified, then every stepth boundary will be returned; for example, for the d3.timeDay interval a step of 2 will return every other day. If step is not an integer, it is floored.
As you've already stated in your own answer, it seems like a known issue.
Anyway, why don't use write your own logic to divide the day into 3-hours chunks? This way we don't need to rely on d3d3's .range method;
let startDate = new Date("2021-03-14T23:00:00.000Z");
let endDate = new Date("2021-03-15T23:00:00.000Z");
var dayInThreeHourPeriods = [ startDate ];
while (endDate > startDate) {
startDate = new Date(startDate.getTime() + (60 * 60 * 3 * 1000));
dayInThreeHourPeriods.push(startDate);
}
console.log(dayInThreeHourPeriods);
Updated JSFiddle
Turns out this is a known issue.
What people tend to do is add a small time period and suddenly it's inclusive:
d3.range(min, max+0.001)
or in my case:
const dayInThreeHourPeriods = d3.timeHour.every(3).range(startDate, d3.timeHour.offset(endDate, 1));
Not ideal. Look there's a proposal to have 'rangeInclusive' which would be better already. But there is no activity on that issue.
If anyone has a better idea for the time being I'd be interested.

seconds to "DD:HH:mm:ss" with moment() [duplicate]

This question already has an answer here:
How to use moment.js to get remaining hours, minutes, and seconds from a unix timestamp?
(1 answer)
Closed 2 years ago.
I am trying to convert seconds to DD:HH:mm:ss format or other formats like (YYYYMMDD)
function secToFormat(seconds, format){
return moment.utc(seconds * 1000).format(format);
}
// works well.
console.log(secToFormat(40,"HH:mm:ss"));
console.log(secToFormat(100,"HH:mm:ss"));
console.log(secToFormat(1800,"HH:mm:ss"));
console.log(secToFormat(18800,"HH:mm:ss"));
console.log(secToFormat(86300,"HH:mm:ss"));
// doesn't work I expected.
console.log(secToFormat(40,"DD:HH:mm:ss")); //it returns 01:00:00:40 but I expect 00:00:00:40
console.log(secToFormat(100,"DD:HH:mm:ss")); //it returns 01:00:01:40 but I expect 00:00:01:40
console.log(secToFormat(86300,"DD:HH:mm:ss")); //it returns 01:23:58:20 but I expect 00:23:58:20
console.log(secToFormat(86400*2,"DD:HH:mm:ss")); //it returns 03:00:00:00 but I expect 02:00:00:00
// it also doesn't work with another format.
console.log(secToFormat(40, "MM:DD:HH:mm:ss")); // I want to get 00:00:00:00:40
console.log(secToFormat(100, "MM:DD:HH:mm:ss")); // I want to get 00:00:00:01:40
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>
I understand why it happens because it starts at 1970-01-01 00:00:00.
but I want to edit it what I expect.
How can I achieve it?
You can use moment.js' durations, however they don't have much in the way of formatting, e.g.
let seconds = 28763827;
let duration = moment.duration(seconds, 'seconds');
console.log('Default ISO: ' + duration); // "PT7989H57M7S"
console.log('Moment humanized: ' + duration.humanize()); // a year
console.log('Moment days: ' + duration.asDays()); // 332.91466435185185
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>
Consider writing your own function to convert to a format like d.HH:mm:ss, e.g.
function secsToTime(secs) {
let d = secs / 8.64e4 | 0;
let H = (secs % 8.64e4) / 3.6e3 | 0;
let m = (secs % 3.6e3) / 60 | 0;
let s = secs % 60;
let z = n=> (n < 10? '0' : '') + n;
return `${d}.${z(H)}:${z(m)}:${z(s)}`
}
let seconds = 28763827;
console.log(secsToTime(seconds));
Using moment-duration-format to implement.
It is actually the "officially referenced" way (by momentjs author in both issues and docs). Explanation and examples here in my other answer:
How to use moment.js to get remaining hours, minutes, and seconds from a unix timestamp?
#RobG's answer is a great base for rolling your own, and I am tempted to edit it into my answer in above link. But note that moment-duration-format already exists and is the sanctioned way to do it, as well as being an actively updated library, and really satisfies most any use case I can think of (eg: drop-in one statement replacement in OP's example code).
It is also possible to extract the data directly from duration's internal variable _data. Though, I really don't recommend doing that. I have a rough demo of that in the other answer.
function secToFormat(seconds, format){
return moment.duration(seconds,'seconds').format(format, {trim: false});
// trim: false so it doesn't trim off 0 values
// (so last one would be 01:40 instead of 00:00:00:01:40 if trim: true)
}
// works well.
console.log(secToFormat(40,"HH:mm:ss"));
console.log(secToFormat(100,"HH:mm:ss"));
console.log(secToFormat(1800,"HH:mm:ss"));
console.log(secToFormat(18800,"HH:mm:ss"));
console.log(secToFormat(86300,"HH:mm:ss"));
// doesn't work I expected.
console.log(secToFormat(40,"DD:HH:mm:ss")); //it returns 01:00:00:40 but I expect 00:00:00:40
console.log(secToFormat(100,"DD:HH:mm:ss")); //it returns 01:00:01:40 but I expect 00:00:01:40
console.log(secToFormat(86300,"DD:HH:mm:ss")); //it returns 01:23:58:20 but I expect 00:23:58:20
console.log(secToFormat(86400*2,"DD:HH:mm:ss")); //it returns 03:00:00:00 but I expect 02:00:00:00
// it also doesn't work with another format.
console.log(secToFormat(40, "MM:DD:HH:mm:ss")); // I want to get 00:00:00:00:40
console.log(secToFormat(100, "MM:DD:HH:mm:ss")); // I want to get 00:00:00:01:40
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>
<!-- moment-duration-format plugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/2.3.1/moment-duration-format.min.js"></script>

How can I convert a date into an integer?

I have an array of dates and have been using the map function to iterate through it, but I can't figure out the JavaScript code for converting them into integers.
This is the array of dates:
var dates_as_int = [
"2016-07-19T20:23:01.804Z",
"2016-07-20T15:43:54.776Z",
"2016-07-22T14:53:38.634Z",
"2016-07-25T14:39:34.527Z"
];
var dates = dates_as_int.map(function(dateStr) {
return new Date(dateStr).getTime();
});
=>
[1468959781804, 1469029434776, 1469199218634, 1469457574527]
Update:
ES6 version:
const dates = dates_as_int.map(date => new Date(date).getTime())
The getTime() method on the Date returns an “ECMAScript epoch”, which is the same as the UNIX epoch but in milliseconds. This is important to note as some other languages use UNIX timestamps which are in in seconds.
The UNIX timestamp and is equivalent to the number of milliseconds since January 1st 1970. This is a date you might have seen before in databases or some apps, and it’s usually the sign of a bug.
Using the builtin Date.parse function which accepts input in ISO8601 format and directly returns the desired integer return value:
var dates_as_int = dates.map(Date.parse);
Here what you can try:
var d = Date.parse("2016-07-19T20:23:01.804Z");
alert(d); //this is in milliseconds
You can run it through Number()
var myInt = Number(new Date(dates_as_int[0]));
If the parameter is a Date object, the Number() function returns the number of milliseconds since midnight January 1, 1970 UTC.
Use of Number()
if your format date is YYYY/M/D you can use this code :
let yourDate = momentjs(new Date().toLocaleDateString(), 'M/D/YYYY').format('YYYY-MM-DD');
let newDate = Number(yourDate.slice(0, 10).split('-').join(''));

Trying to add a timer to my website to countdown days

I'm trying to get a timer to count down to a date by days and I don't know why this isn't working it just says NaN
function daysUntil24thApril2016() {
var april2016 = new Date(24, 4, 2016);
var difference = april2016.getMilliseconds - Date.now().getMilliseconds;
return difference / 1000 / 60 / 60 / 24;
}
$(document).ready(function() {
console.log("asdasd")
$('#dateTime').text(daysUntil24thApril2016());
});
There are several mistakes you made in your script, I'll try to explain each to help you understand it and finally give you a corrected script the way you wrote it:
new Date() wants the year first, then month - 1 and finally the days. So to get the 24.04.2016, you have to do new Date(2016, 3, 24)
For a Date there is a getMilliseconds function, but it returns the milliseconds part of that date, not the unix timestamp you wanted
.getTime() is the function to get the unix timestamp in milliseconds from this date
Date.now() already returns the unix timestamp (a number), there is no getMilliseconds() for that and therefore it returned undefined
Even if there were a getMilliseconds function, the way you wrote it without the braces () would not have called it anyway but returned the function. They way you wrote it resulted in var difference = function - undefined which is NaN: "Not a number".
Therefore difference was no number in your example (it was Nan) and you cannot do any math with it obviously, it stays NaN
Using Math.floor will give you full days
See below for a version of your script where the points above are corrected.
function daysUntil24thApril2016() {
var april2016 = new Date(2016, 3, 24);
var difference = april2016.getTime() - Date.now();
return Math.floor(difference / 1000 / 60 / 60 / 24);
}
$(document).ready(function() {
$('#dateTime').text(daysUntil24thApril2016());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dateTime"></div>
Something like this will solve your problem:
function daysUntil24thApril2016() {
var april2016 = new Date("2015-04-24");
var difference = Date.now()-april2016;
return Math.floor((difference) / (1000*60*60*24))
}
$(document).ready(function() {
console.log(daysUntil24thApril2016());
});
When you subtract one Date object from another you will get the time difference in milliseconds. Using Math.floor() will return a whole (integer) number of days.

Categories

Resources