How can I find the amount of seconds passed from t

2019-01-07 23:18发布

I need a function that gives me how many seconds passed from the midnight. I am currently using System.currentTimeMillis() but it gives me the UNIX like timestamp.

It would be a bonus for me if I could get the milliseconds too.

标签: java time
8条回答
三岁会撩人
2楼-- · 2019-01-07 23:40

java.time

Using the java.time framework built into Java 8 and later. See Tutorial.

import java.time.LocalTime
import java.time.ZoneId

LocalTime now = LocalTime.now(ZoneId.systemDefault()) // LocalTime = 14:42:43.062
now.toSecondOfDay() // Int = 52963

It is good practice to explicit specify ZoneId, even if you want default one.

查看更多
Evening l夕情丶
3楼-- · 2019-01-07 23:43

Like @secmask, if you need milli-seconds since GMT midnight, try

long millisSinceGMTMidnight = System.currentTimeMillis() % (24*60*60*1000);
查看更多
Evening l夕情丶
4楼-- · 2019-01-07 23:44

The simplest and fastest method to get the seconds since midnight for the current timezone:

One-time setup:

static final long utcOffset = TimeZone.getDefault().getOffset(System.currentTimeMillis());

If you use Apache Commons, you can use DateUtils.DAY_IN_MILLIS, otherwise define:

static final long DAY_IN_MILLIS = 24 * 60 * 60 * 1000;

And then, whenever you need the time...:

int seconds = (int)((System.currentTimeMillis() + utcOffset) % DateUtils.DAY_IN_MILLIS / 1000);

Note that you'll need to re-setup if there's a possibility that your program will run long enough, and Daylight Saving Times change occurs...

查看更多
倾城 Initia
5楼-- · 2019-01-07 23:48

If you're using Java >= 8, this is easily done :

ZonedDateTime now = ZonedDateTime.now();
ZonedDateTime midnight = now.atStartOfDay()
Duration duration = Duration.between(midnight, now);
long secondsPassed = duration.getSeconds();

If you're using Java 7 or less, you have to get the date from midnight via Calendar, and then substract.

Calendar c = Calendar.getInstance();
long now = c.getTimeInMillis();
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long passed = now - c.getTimeInMillis();
long secondsPassed = passed / 1000;
查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-01-07 23:51

Use getTime().getTime() instead of getTimeInMillis() if you get an error about calendar being protected. Remember your imports:

import java.util.*; 

will include them all while you are debugging:

    Calendar now = Calendar.getInstance();
    Calendar midnight = Calendar.getInstance();
    midnight.set(Calendar.HOUR_OF_DAY, 0);
    midnight.set(Calendar.MINUTE, 0);
    midnight.set(Calendar.SECOND, 0);
    midnight.set(Calendar.MILLISECOND, 0);
    long ms = now.getTime().getTime() - midnight.getTime().getTime();
    totalMinutesSinceMidnight = (int) (ms / 1000 / 60);
查看更多
混吃等死
7楼-- · 2019-01-07 23:55
(System.currentTimeMillis()/1000) % (24 * 60 * 60)
查看更多
登录 后发表回答