Android Get Current timestamp?

前端 未结 12 733
灰色年华
灰色年华 2020-11-27 09:53

I want to get the current timestamp like that : 1320917972

int time = (int) (System.currentTimeMillis());
Timestamp tsTemp = new Timestamp(t         


        
相关标签:
12条回答
  • 2020-11-27 10:46

    Solution in Kotlin:

    val nowInEpoch = Instant.now().epochSecond
    

    Make sure your minimum SDK version is 26.

    0 讨论(0)
  • 2020-11-27 10:47

    1320917972 is Unix timestamp using number of seconds since 00:00:00 UTC on January 1, 1970. You can use TimeUnit class for unit conversion - from System.currentTimeMillis() to seconds.

    String timeStamp = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
    
    0 讨论(0)
  • 2020-11-27 10:47

    You can get Current timestamp in Android by trying below code

    time.setText(String.valueOf(System.currentTimeMillis()));
    

    and timeStamp to time format

    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
    String dateString = formatter.format(new Date(Long.parseLong(time.getText().toString())));
    time.setText(dateString);
    
    0 讨论(0)
  • 2020-11-27 10:48

    It's simple use:

    long millis = new Date().getTime();
    

    if you want it in particular format then you need Formatter like below

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String millisInString  = dateFormat.format(new Date());
    
    0 讨论(0)
  • 2020-11-27 10:51

    This code is Kotlin version. I have another idea to add a random shuffle integer in last digit for giving variance epoch time.

    Kotlin version

    val randomVariance = (0..100).shuffled().first()
    val currentEpoch = (System.currentTimeMilis()/1000) + randomVariance
    
    val deltaEpoch = oldEpoch - currentEpoch
    

    I think it will be better using this kode then depend on android version 26 or more

    0 讨论(0)
  • 2020-11-27 10:52

    From developers blog:

    System.currentTimeMillis() is the standard "wall" clock (time and date) expressing milliseconds since the epoch. The wall clock can be set by the user or the phone network (see setCurrentTimeMillis(long)), so the time may jump backwards or forwards unpredictably. This clock should only be used when correspondence with real-world dates and times is important, such as in a calendar or alarm clock application. Interval or elapsed time measurements should use a different clock. If you are using System.currentTimeMillis(), consider listening to the ACTION_TIME_TICK, ACTION_TIME_CHANGED and ACTION_TIMEZONE_CHANGED Intent broadcasts to find out when the time changes.

    0 讨论(0)
提交回复
热议问题