Android는 현재 타임 스탬프를 가져 옵니까?
현재 타임 스탬프를 다음과 같이 얻고 싶습니다 : 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 이후의 시간 (초)을 사용하는 유닉스 타임 스탬프 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());
누군가가 내가 필요로하는 것과 똑같은 것을 필요로 할 경우를 대비하여 파일 이름으로 사용할 수있는 사람이 읽을 수있는 타임 스탬프가 있습니다.
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;
}
}
그냥 사용
long millis = new Date().getTime();
긴 시간으로 현재 시간을 가져 오기
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의 답변과 동일합니다. 출력은 이전과 동일합니다.
질문 : Android에서 java.time을 사용할 수 있습니까?
예. java.time은 이전 및 최신 Android 장치에서 잘 작동합니다. 최소한 Java 6 만 있으면됩니다 .
- Java 8 이상 및 최신 Android 장치 (API 레벨 26부터)에는 최신 API가 내장되어 있습니다.
- Android 이외의 Java 6 및 7에서는 새 클래스의 백 포트 인 ThreeTen Backport를 가져옵니다 (ThreeTen for JSR 310; 맨 아래 링크 참조).
- (구형) Android에서는 Android 버전의 ThreeTen Backport를 사용합니다. 이를 ThreeTenABP라고합니다.
org.threeten.bp
서브 패키지 를 사용 하여 날짜 및 시간 클래스를 가져와야합니다 .
연결
- 오라클 튜토리얼 : 날짜 시간 사용하는 방법을 설명
java.time
. - JSR (Java Specification Request) 310 에서
java.time
설명되었다. - ThreeTen Backport project ,
java.time
Java 6 및 7 의 백 포트 (ThreeTen for JSR-310). - ThreeTenABP , Android 버전의 ThreeTen Backport
- 질문 : Android 프로젝트에서 ThreeTenABP를 사용하는 방법을 매우 철저하게 설명합니다.
코 틀린 솔루션 :
val nowInEpoch = Instant.now().epochSecond
최소 SDK 버전이 26인지 확인하십시오.
Hits의 답변을 사용하는 것이 좋지만 로케일 형식을 추가하면 Android 개발자가 권장 하는 방법입니다 .
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;
}
이것들을보십시오
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);
참고 URL : https://stackoverflow.com/questions/8077530/android-get-current-timestamp
'Programing' 카테고리의 다른 글
문자열과 ArrayBuffer 사이의 변환 (0) | 2020.04.19 |
---|---|
IntelliJ IDEA에서 맞춤법 검사를 사용하지 않도록 설정 (0) | 2020.04.18 |
서로 다른 두 목록에 정확히 동일한 요소가 포함되어 있는지 확인하는 간단한 방법은 무엇입니까? (0) | 2020.04.18 |
코드의 maven pom.xml에서 버전 검색 (0) | 2020.04.18 |
Nodejs가 Windows에서 설치된 모듈을 찾을 수 없습니다 (0) | 2020.04.18 |