programing

Android Get Current 타임스탬프?

prostudy 2022. 7. 8. 21:53
반응형

Android Get Current 타임스탬프?

현재 타임스탬프 1320917972를 취득하고 싶다.

int time = (int) (System.currentTimeMillis());
Timestamp tsTemp = new Timestamp(time);
String ts =  tsTemp.toString();

해결책은 다음과 같습니다.

Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();

개발자 블로그:

System.currentTimeMillis()는 에폭 이후의 밀리초를 나타내는 표준 "벽" 클럭(시간 및 날짜)입니다.벽시계는 사용자 또는 전화 네트워크에 의해 설정할 수 있습니다(setCurrentTimeMillis(long) 참조).따라서 시간이 예측할 수 없이 뒤로 또는 앞으로 이동할 수 있습니다.이 시계는 캘린더나 알람시계 응용 프로그램 등 실제 날짜 및 시간과의 대응이 중요한 경우에만 사용해야 합니다.간격 또는 경과 시간 측정에는 다른 클럭을 사용해야 합니다.사용하시는 경우System.currentTimeMillis(), 를 듣는 것을 고려합니다.ACTION_TIME_TICK,ACTION_TIME_CHANGED그리고.ACTION_TIMEZONE_CHANGED시간이 언제 바뀌는지 알아내기 위해 브로드캐스트를 의도합니다.

1320917972는 1970년1월 1일 00:00:00 UTC 이후의 초수를 사용한 Unix 타임스탬프입니다.사용할 수 있습니다.TimeUnit단위 변환 클래스 - 시작System.currentTimeMillis()초단위로 이동합니다.

String timeStamp = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));

SimpleDateFormat 클래스를 사용할 수 있습니다.

SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
String format = s.format(new Date());

현재의 타임스탬프를 취득하려면 , 다음의 방법을 사용합니다.난 괜찮아.

/**
 * 
 * @return yyyy-MM-dd HH:mm:ss formate date as string
 */
public static String getCurrentTimeStamp(){
    try {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentDateTime = dateFormat.format(new Date()); // Find todays date

        return currentDateTime;
    } catch (Exception e) {
        e.printStackTrace();

        return null;
    }
}

간단한 사용법:

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

특정 포맷을 원하시면 아래와 같은 포맷터가 필요합니다.

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String millisInString  = dateFormat.format(new Date());

Android에서 아래 코드를 시도하면 현재 타임스탬프를 얻을 수 있습니다.

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

및 timeStamp to time 형식

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateString = formatter.format(new Date(Long.parseLong(time.getText().toString())));
time.setText(dateString);

여기 사람이 읽을 수 있는 타임 스탬프가 있습니다.파일명에 사용할 수 있습니다.혹시 누군가가 제가 필요로 하는 것과 같은 것을 필요로 할 때를 대비해서입니다.

package com.example.xyz;

import android.text.format.Time;

/**
 * Clock utility.
 */
public class Clock {

    /**
     * Get current time in human-readable form.
     * @return current time as a string.
     */
    public static String getNow() {
        Time now = new Time();
        now.setToNow();
        String sTime = now.format("%Y_%m_%d %T");
        return sTime;
    }
    /**
     * Get current time in human-readable form without spaces and special characters.
     * The returned value may be used to compose a file name.
     * @return current time as a string.
     */
    public static String getTimeStamp() {
        Time now = new Time();
        now.setToNow();
        String sTime = now.format("%Y_%m_%d_%H_%M_%S");
        return sTime;
    }

}

Kotlin 솔루션:

val nowInEpoch = Instant.now().epochSecond

최소 SDK 버전이 26인지 확인하십시오.

다음은 가장 널리 알려진 방법의 비교 목록입니다.

java.time

나는 현대적 해답에 기여하고 싶다.

    String ts = String.valueOf(Instant.now().getEpochSecond());
    System.out.println(ts);

방금 실행 중인 경우의 출력:

1543320466

많은 사람들에게 1000으로 나누면 놀랄 일은 아니지만, 자신의 시간을 변환하는 것은 매우 빨리 읽기가 어려울 수 있기 때문에 피할 수 있을 때 시작하는 것은 나쁜 습관입니다.

Instant현재 사용하고 있는 클래스는 최신 Java 날짜 및 시간 API인 java.time의 일부입니다.새로운 Android 버전, API 레벨 26 이상에 내장되어 있습니다.이전 Android용으로 프로그래밍하는 경우 백포트를 사용할 수 있습니다(아래 참조).그렇게 하고 싶지 않다면, 당연히 기본 제공 변환을 사용할 것입니다.

    String ts = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
    System.out.println(ts);

이것은 sealskej의 답변과 동일합니다.출력은 이전과 동일합니다.

질문: 안드로이드에서 java.time을 사용할 수 있습니까?

네, java.time은 오래된 Android 기기와 새로운 기기에서 잘 작동합니다.적어도 Java 6이 필요합니다.

  • Java 8 이후 및 새로운 Android 디바이스(API 레벨 26부터)에서는 최신 API가 내장되어 있습니다.
  • 비 Android Java 6 및7에서는 새로운 클래스의 백포트인 ThreeTen Backport를 가져옵니다(JSR 310의 경우 ThreeTen, 하단의 링크 참조).
  • Android(안드로이드) ThreeTen Backport(쓰리텐 백포트)쓰리텐ABP로 하다 Import하다에서 .org.threeten.bp브브서서

링크

Hits의 답변을 사용할 것을 권장합니다만, 로케일 형식을 추가하면, Android Developers는 다음과 같이 권장하고 있습니다.

try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        return dateFormat.format(new Date()); // Find todays date
    } catch (Exception e) {
        e.printStackTrace();

        return null;
    }

이 코드는 Kotlin 버전입니다.분산 에폭 시간을 주기 위해 마지막 자릿수에 랜덤 셔플 정수를 추가하는 또 다른 아이디어가 있습니다.

코틀린 버전

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

val deltaEpoch = oldEpoch - currentEpoch

안드로이드 버전 26 이상에 따라서는 이 Kode를 사용하는 것이 좋다고 생각합니다.

다음은 Kotlin에 대한 또 다른 해결책입니다.

val timeStamp = Calendar.getInstance().time

출력(이 명령어만 실행)의 예:

"3월 25일 금요일 13:56:51 GMT+01:00 2022"

언급URL : https://stackoverflow.com/questions/8077530/android-get-current-timestamp

반응형