Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Current date to integer

Tags:

java

date

I want to convert the current date to integer value. By default, it returns long. When I try to convert long to integer, and afterwards I convert the integer value to date, means it shows 1970's date,

 int i = (int) new Date().getTime();
 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(i));

the output as follows:

Integer : 1292838124
Long : 1345617601771
Long date : Wed Aug 22 12:10:01 IST 2012
Int Date : Fri Jan 16 04:37:18 IST 1970

Any one please help me out, how to convert current date to integer(10 digit number)?

like image 486
Bathakarai Avatar asked Aug 22 '12 06:08

Bathakarai


7 Answers

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
like image 62
shonky linux user Avatar answered Oct 22 '22 06:10

shonky linux user


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.

like image 32
k_ssup Avatar answered Oct 22 '22 06:10

k_ssup


tl;dr

Instant.now().getEpochSecond()  // The number of seconds from the Java epoch of 1970-01-01T00:00:00Z.

Details

As others stated, a 32-bit integer cannot hold a number big enough for the number of seconds from the epoch (beginning of 1970 in UTC) and now. You need 64-bit integer (a long primitive or Long object).

java.time

The other answers are using old legacy date-time classes. They have been supplanted by the java.time classes.

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.

Instant now = instant.now() ;

You can interrogate for the number of milliseconds since the epoch. Beware this means a loss of data, truncating nanoseconds to milliseconds.

long millisecondsSinceEpoch = now.toEpochMilli() ;

If you want a count of nanoseconds since epoch, you will need to do a bit of math as the class oddly lacks a toEpochNano method. Note the L appended to the billion to provoke the calculation as 64-bit long integers.

long nanosecondsSinceEpoch = ( instant.getEpochSecond() * 1_000_000_000L ) + instant.getNano() ;

Whole seconds since epoch

But the end of the Question asks for a 10-digit number. I suspect that means a count of whole seconds since the epoch of 1970-01-01T00:00:00. This is commonly referred to as Unix Time or Posix Time.

We can interrogate the Instant for this number. Again, this means a loss of data with the truncation of any fraction-of-second this object may hold.

long secondsSinceEpoch = now.getEpochSecond() ;  // The number of seconds from the Java epoch of 1970-01-01T00:00:00Z.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

like image 23
Basil Bourque Avatar answered Oct 22 '22 06:10

Basil Bourque


If you need only an integer representing elapsed days since Jan. 1, 1970, you can try these:

// magic number=
// millisec * sec * min * hours
// 1000 * 60 * 60 * 24 = 86400000
public static final long MAGIC=86400000L;

public int DateToDays (Date date){
    //  convert a date to an integer and back again
    long currentTime=date.getTime();
    currentTime=currentTime/MAGIC;
    return (int) currentTime; 
}

public Date DaysToDate(int days) {
    //  convert integer back again to a date
    long currentTime=(long) days*MAGIC;
    return new Date(currentTime);
}

Shorter but less readable (slightly faster?):

public static final long MAGIC=86400000L;

public int DateToDays (Date date){
    return (int) (date.getTime()/MAGIC);
}

public Date DaysToDate(int days) {
    return new Date((long) days*MAGIC);
}

Hope this helps.

EDIT: This could work until Fri Jul 11 01:00:00 CET 5881580

like image 31
Rudy Avatar answered Oct 22 '22 06:10

Rudy


Do you need something like this(without time)?

public static Integer toJulianDate(Date pDate) {
if (pDate == null) {
  return null;
}
Calendar lCal = Calendar.getInstance();
lCal.setTime(pDate);
int lYear = lCal.get(Calendar.YEAR);
int lMonth = lCal.get(Calendar.MONTH) + 1;
int lDay = lCal.get(Calendar.DATE);
int a = (14 - lMonth) / 12;
int y = lYear + 4800 - a;
int m = lMonth + 12 * a - 3;
return lDay + (153 * m + 2) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 32045;
}
like image 32
s_bei Avatar answered Oct 22 '22 08:10

s_bei


I've solved this as is shown below:

    long year = calendar.get(Calendar.YEAR);
    long month = calendar.get(Calendar.MONTH) + 1;
    long day = calendar.get(Calendar.DAY_OF_MONTH);
    long calcDate = year * 100 + month;
    calcDate = calcDate * 100 + day;
    System.out.println("int: " + calcDate);
like image 26
Zamir García Avatar answered Oct 22 '22 06:10

Zamir García


Try This

Calendar currentDay= Calendar.getInstance();
int currDate= currentDay.get(Calendar.DATE);
int currMonth= currentDay.get(Calendar.MONTH);
int currYear= currentDay.get(Calendar.YEAR);
System.out.println(currDate + "-" +  currMonth + "-" + currYear);

an alternative way using LocalDate.

LocalDate today = LocalDate.now();
int currentDate= today.getDayOfMonth();
int currentMonth= today.getMonthValue();
int currentYear= today.getYear()
like image 26
Abhishek Avatar answered Oct 22 '22 08:10

Abhishek