DomX23
DomX23

Reputation: 887

.getTime() Alternative without milliseconds

Is there a way to use the Date().getTime() function without getting the time in milliseconds? If not is there a substitute for .getTime() which will only give me the precision in minutes?

Also I'm not sure how to just strip the milliseconds out of the date object.

var time = new Date().getTime()

Output: 1426515375925

Upvotes: 21

Views: 35253

Answers (8)

Elmatsidis Paul
Elmatsidis Paul

Reputation: 465

new Date().toLocaleTimeString().split(':').slice(0, 2).join(':')

Will return "hh:MM"

Upvotes: 0

SnelleFiets
SnelleFiets

Reputation: 83

The simplest way to remove the milliseconds:

Long date = new Date().getTime() / 1000 * 1000

1582302824091L becomes 1582302824000L
2020-02-21 17:33:44.091 becomes 2020-02-21 17:33:44.0

Upvotes: 2

Marek
Marek

Reputation: 4079

In my case (date without miliseconds), I wanted miliseconds to always be zero, so it would be like:

hh:mm:ss:000

Here is how I achived it:

var time = new Date().getTime();
// Make miliseconds = 0 (precision full seconds)
time -= time % 1000;

Maybe it will be useful for someone

Upvotes: 8

9Deuce
9Deuce

Reputation: 676

You can pull each portion of the time you want and put in a formatted string, like

var time = new Date().getHours() + ":" + new Date().getMinutes() + ":" + new Date().getSeconds();

Upvotes: 0

Darkmouse
Darkmouse

Reputation: 1939

By default, the time is set to the number of miliseconds since the epoch. To get the number of seconds, simply divide that number by 1000, and round to get a whole number

Math.round(new Date().getTime()/1000)

To get the number of minutes divide that number by 60

Math.round(new Date().getTime()/1000/60)

Upvotes: 0

David Laberge
David Laberge

Reputation: 16081

Here a quick way to remove the milisecont from the getTime

var milli = new Date().getTime()
var timeWithoutMilli = Math.floor(milli/1000);

That will return the number of seconds

Upvotes: 2

inorganik
inorganik

Reputation: 25535

Date object of the current time:

var time = new Date();

Upvotes: 0

James Donnelly
James Donnelly

Reputation: 128856

Simple arithmetic. If you want the value in seconds, divide the milliseconds result by 1000:

var seconds = new Date().getTime() / 1000;

You might want to call Math.floor() on that to remove any decimals though:

var seconds = Math.floor(new Date().getTime() / 1000);

Is there a different function I can use that will give me only the minutes since 1/1/1970, I just dont want the number to be as precise.

Certainly, divide the seconds by 60, or divide the milliseconds by 60000:

var minutes = Math.floor(new Date().getTime() / 60000);

var milliseconds = 1426515375925,
    seconds = Math.floor(milliseconds / 1000),  // 1426515375
    minutes = Math.floor(milliseconds / 60000); // 23775256

Upvotes: 47

Related Questions