close

How can I convert a date into an integer?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How can I convert a date into an integer? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How can I convert a date into an integer ?

  1. How can I convert a date into an integer ?

    can I convert a date into an integer In order to get current date as integer(10 digit number), you need to divide the long returned from new Date().getTime() by 1000.
    This will be in int range and is good until 18 Jan 2038.

  2. How can I convert a date into an integer ?

    can I convert a date into an integer In order to get current date as integer(10 digit number), you need to divide the long returned from new Date().getTime() by 1000.
    This will be in int range and is good until 18 Jan 2038.

Method 1

The issue is that an Integer is not large enough to store a current date, you need to use a Long.

The date is stored internally as the number of milliseconds since 1/1/1970.

The maximum Integer value is 2147483648, whereas the number of milliseconds since 1970 is currently in the order of 1345618537869

Putting the maximum integer value into a date yields Monday 26th January 1970.

Edit: Code to display division by 1000 as per comment below:

    int i = (int) (new Date().getTime()/1000);
    System.out.println("Integer : " + i);
    System.out.println("Long : "+ new Date().getTime());
    System.out.println("Long date : " + new Date(new Date().getTime()));
    System.out.println("Int Date : " + new Date(((long)i)*1000L));

Integer : 1345619256
Long : 1345619256308
Long date : Wed Aug 22 16:37:36 CST 2012
Int Date : Wed Aug 22 16:37:36 CST 2012

Method 2

In order to get current date as integer(10 digit number), you need to divide the long returned from new Date().getTime() by 1000.

This will be in int range and is good until 18 Jan 2038.

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment