簡體   English   中英

如何在android中將毫秒轉換為日期格式?

[英]how to convert milliseconds to date format in android?

我有毫秒。 我需要將其轉換為日期格式

例子:

23/10/2011

如何實現?

試試這個示例代碼:-

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;


public class Test {

/**
 * Main Method
 */
public static void main(String[] args) {
    System.out.println(getDate(82233213123L, "dd/MM/yyyy hh:mm:ss.SSS"));
}


/**
 * Return date in specified format.
 * @param milliSeconds Date in milliseconds
 * @param dateFormat Date format 
 * @return String representing date in specified format
 */
public static String getDate(long milliSeconds, String dateFormat)
{
    // Create a DateFormatter object for displaying date in specified format.
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);

    // Create a calendar object that will convert the date and time value in milliseconds to date. 
     Calendar calendar = Calendar.getInstance();
     calendar.setTimeInMillis(milliSeconds);
     return formatter.format(calendar.getTime());
}
}

我希望這有助於...

毫秒值轉換為Date實例並將其傳遞給選擇的格式化程序。

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); 
String dateString = formatter.format(new Date(dateInMillis)));
public static String convertDate(String dateInMilliseconds,String dateFormat) {
    return DateFormat.format(dateFormat, Long.parseLong(dateInMilliseconds)).toString();
}

調用這個函數

convertDate("82233213123","dd/MM/yyyy hh:mm:ss");
DateFormat.getDateInstance().format(dateInMS);

tl;博士

Instant.ofEpochMilli( myMillisSinceEpoch )           // Convert count-of-milliseconds-since-epoch into a date-time in UTC (`Instant`).
    .atZone( ZoneId.of( "Africa/Tunis" ) )           // Adjust into the wall-clock time used by the people of a particular region (a time zone). Produces a `ZonedDateTime` object.
    .toLocalDate()                                   // Extract the date-only value (a `LocalDate` object) from the `ZonedDateTime` object, without time-of-day and without time zone.
    .format(                                         // Generate a string to textually represent the date value.
        DateTimeFormatter.ofPattern( "dd/MM/uuuu" )  // Specify a formatting pattern. Tip: Consider using `DateTimeFormatter.ofLocalized…` instead to soft-code the formatting pattern.
    )                                                // Returns a `String` object.
    

時間

現代方法使用java.time類取代所有其他答案使用的麻煩的舊遺留日期時間類。

假設自 UTC 時間 1970 年第一個時刻的紀元參考以來有很long的毫秒數,1970-01-01T00:00:00Z…

Instant instant = Instant.ofEpochMilli( myMillisSinceEpoch ) ;

獲取日期需要時區。 對於任何給定時刻,日期因地區而異。

ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;  // Same moment, different wall-clock time.

提取僅限日期的值。

LocalDate ld = zdt.toLocalDate() ;

使用標准 ISO 8601 格式生成表示該值的字符串。

String output = ld.toString() ;

生成自定義格式的字符串。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
String output = ld.format( f ) ;

提示:考慮讓java.time自動為您本地化,而不是硬編碼格式模式。 使用DateTimeFormatter.ofLocalized…方法。


關於java.time

java.time框架內置於 Java 8 及更高版本中。 這些類取代麻煩的老傳統日期時間類,如java.util.DateCalendar ,和SimpleDateFormat

要了解更多信息,請參閱Oracle 教程 並在 Stack Overflow 上搜索許多示例和解釋。 規范是JSR 310

現在處於維護模式Joda-Time項目建議遷移到java.time類。

您可以直接與您的數據庫交換java.time對象。 使用符合JDBC 4.2或更高版本的JDBC 驅動程序 不需要字符串,不需要java.sql.*類。 Hibernate 5 & JPA 2.2 支持java.time

從哪里獲得 java.time 類?

試試這個代碼可能會有所幫助,根據您的需要修改它

SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date d = format.parse(fileDate);

我終於找到了對我有用的普通代碼

Long longDate = Long.valueOf(date);

Calendar cal = Calendar.getInstance();
int offset = cal.getTimeZone().getOffset(cal.getTimeInMillis());
Date da = new Date(); 
da = new Date(longDate-(long)offset);
cal.setTime(da);

String time =cal.getTime().toLocaleString(); 
//this is full string        

time = DateFormat.getTimeInstance(DateFormat.MEDIUM).format(da);
//this is only time

time = DateFormat.getDateInstance(DateFormat.MEDIUM).format(da);
//this is only date

簡短有效:

DateFormat.getDateTimeInstance().format(new Date(myMillisValue))
public class LogicconvertmillistotimeActivity extends Activity {
    /** Called when the activity is first created. */
     EditText millisedit;
        Button   millisbutton;
        TextView  millistextview;
        long millislong;
        String millisstring;
        int millisec=0,sec=0,min=0,hour=0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        millisedit=(EditText)findViewById(R.id.editText1);
        millisbutton=(Button)findViewById(R.id.button1);
        millistextview=(TextView)findViewById(R.id.textView1);
        millisbutton.setOnClickListener(new View.OnClickListener() {            
            @Override
            public void onClick(View v) {   
                millisbutton.setClickable(false);
                millisec=0;
                sec=0;
                min=0;
                hour=0;
                millisstring=millisedit.getText().toString().trim();
                millislong= Long.parseLong(millisstring);
                Calendar cal = Calendar.getInstance();
                SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
                if(millislong>1000){
                    sec=(int) (millislong/1000);
                    millisec=(int)millislong%1000;
                    if(sec>=60){
                        min=sec/60;
                        sec=sec%60;
                    }
                    if(min>=60){
                        hour=min/60;
                        min=min%60;
                    }
                }
                else
                {
                    millisec=(int)millislong;
                }
                cal.clear();
                cal.set(Calendar.HOUR_OF_DAY,hour);
                cal.set(Calendar.MINUTE,min);
                cal.set(Calendar.SECOND, sec);
                cal.set(Calendar.MILLISECOND,millisec);
                String DateFormat = formatter.format(cal.getTime());
//              DateFormat = "";
                millistextview.setText(DateFormat);

            }
        });
    }
}
    public static Date getDateFromString(String date) {

    Date dt = null;
    if (date != null) {
        for (String sdf : supportedDateFormats) {
            try {
                dt = new Date(new SimpleDateFormat(sdf).parse(date).getTime());
                break;
            } catch (ParseException pe) {
                pe.printStackTrace();
            }
        }
    }
    return dt;
}

public static Calendar getCalenderFromDate(Date date){
    Calendar cal =Calendar.getInstance();
    cal.setTime(date);return cal;

}
public static Calendar getCalenderFromString(String s_date){
    Date date = getDateFromString(s_date);
    Calendar cal = getCalenderFromDate(date);
    return cal;
}

public static long getMiliSecondsFromString(String s_date){
    Date date = getDateFromString(s_date);
    Calendar cal = getCalenderFromDate(date);
    return cal.getTimeInMillis();
}
public static String toDateStr(long milliseconds, String format)
{
    Date date = new Date(milliseconds);
    SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.US);
    return formatter.format(date);
}

一段時間以來,我一直在尋找一種有效的方法來做到這一點,我發現的最好的方法是:

DateFormat.getDateInstance(DateFormat.SHORT).format(new Date(millis));

優點:

  1. 已本地化
  2. 從 API 1 開始使用 Android
  3. 很簡單的

缺點:

  1. 有限的格式選項。 僅供參考:SHORT 只是一個 2 位數的年份。
  2. 您每次都刻錄一個 Date 對象。 我已經查看了其他選項的來源,與它們的開銷相比,這是一個相當小的開銷。

您可以緩存 java.text.DateFormat 對象,但它不是線程安全的。 如果您在 UI 線程上使用它,這是可以的。

在 Android (Java / Kotlin) 中將紀元格式轉換為 SimpleDateFormat

輸入:1613316655000

輸出:2021-02-14T15:30:55.726Z

在 Java 中

long milliseconds = 1613316655000L;
Date date = new Date(milliseconds);
String mobileDateTime = Utils.getFormatTimeWithTZ(date);

//以String形式返回SimpleDateFormat的方法

public static String getFormatTimeWithTZ(Date currentTime) {
    SimpleDateFormat timeZoneDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
    return timeZoneString = timeZoneDate.format(currentTime);
}

在科特林

var milliseconds = 1613316655000L
var date = Date(milliseconds)
var mobileDateTime = Utils.getFormatTimeWithTZ(date)

//以String形式返回SimpleDateFormat的方法

fun getFormatTimeWithTZ(currentTime:Date):String {
  val timeZoneDate = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault())
  return timeZoneString = timeZoneDate.format(currentTime)
}

這是使用 Kotlin 的最簡單方法

private const val DATE_FORMAT = "dd/MM/yy hh:mm"

fun millisToDate(millis: Long) : String {
    return SimpleDateFormat(DATE_FORMAT, Locale.US).format(Date(millis))
}

為 Android N 及更高版本使用 SimpleDateFormat。 使用早期版本的日歷,例如:

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        fileName = new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss").format(new Date());
        Log.i("fileName before",fileName);
    }else{
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH,1);
        String zamanl =""+cal.get(Calendar.YEAR)+"-"+cal.get(Calendar.MONTH)+"-"+cal.get(Calendar.DAY_OF_MONTH)+"-"+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+":"+cal.get(Calendar.SECOND);

        fileName= zamanl;
        Log.i("fileName after",fileName);
    }

輸出:
fileName before: 2019-04-12-07:14:47 // 使用 SimpleDateFormat
fileName after: 2019-4-12-7:13:12 // 使用日歷

fun convertLongToTimeWithLocale(){
    val dateAsMilliSecond: Long = 1602709200000
    val date = Date(dateAsMilliSecond)
    val language = "en"
    val formattedDateAsDigitMonth = SimpleDateFormat("dd/MM/yyyy", Locale(language))
    val formattedDateAsShortMonth = SimpleDateFormat("dd MMM yyyy", Locale(language))
    val formattedDateAsLongMonth = SimpleDateFormat("dd MMMM yyyy", Locale(language))
    Log.d("month as digit", formattedDateAsDigitMonth.format(date))
    Log.d("month as short", formattedDateAsShortMonth.format(date))
    Log.d("month as long", formattedDateAsLongMonth.format(date))
}

輸出:

month as digit: 15/10/2020
month as short: 15 Oct 2020 
month as long : 15 October 2020

您可以根據需要更改定義為“語言”的值。 這是所有語言代碼: Java 語言代碼

您可以以毫秒為單位構造 java.util.Date。 然后使用 java.text.DateFormat 將其轉換為字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM