0

The below function gives the unixtime for the current time in the device

    public static long get_unix_time2(long seconds_since_midnight_gmt,
        int day_of_month) {
    long m_time = 0;
    Calendar cal = Calendar.getInstance();

    cal.set(Calendar.MONTH, cal.get(Calendar.MONTH));
    cal.set(Calendar.YEAR, cal.get(Calendar.YEAR));
    cal.set(Calendar.DAY_OF_MONTH, day_of_month); 
    m_time = cal.getTime().getTime();

    //Date current = Calendar.getInstance().getTime();
    //Date dateTime = new Date();
    //long diffInSeconds = (current.getTime() - dateTime.getTime()) / 1000;
    //long min = (diffInSeconds = (diffInSeconds / 60)) >= 60 ?   //diffInSeconds  % 60
        //  : diffInSeconds;

    // m_time = m_time - (min * -3600 * 1000);

    return m_time;
}

How can I change the unixtime so that the time from the device is replaced with "seconds_since_midnight_gmt" value recieved as parameter.

user1382802
  • 618
  • 2
  • 12
  • 24

2 Answers2

0

You can set the values of the Calendarobject.

cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.SECOND, (int) seconds_since_midnight_gmt);
SubOptimal
  • 22,518
  • 3
  • 53
  • 69
0

java.time

The legacy date-time API (java.util date-time types and their formatting type, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.

Solution using the modern API:

import java.time.Duration;
import java.time.YearMonth;
import java.time.ZoneId;

public class Main {
    public static void main(String[] args) {
        //Test
        System.out.println(getUnixTime2(10000, 16));
    }

    public static long getUnixTime2(long secondsSinceMidnightGmt, int dayOfMonth) {
        return YearMonth.now()
                .atDay(dayOfMonth)
                .atStartOfDay(ZoneId.systemDefault())
                .plus(Duration.ofSeconds(secondsSinceMidnightGmt))
                .toInstant()
                .toEpochMilli();
    }
}

Output:

1621129600000

Learn more about the modern date-time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110