簡體   English   中英

如何將字符串Date轉換為long millseconds

[英]How to convert a string Date to long millseconds

我在字符串中有一個日期,類似於“2012年12月12日”。 如何將其轉換為毫秒(長)?

使用SimpleDateFormat

String string_date = "12-December-2012";

SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
try {
    Date d = f.parse(string_date);
    long milliseconds = d.getTime();
} catch (ParseException e) {
    e.printStackTrace();
}
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date date = (Date)formatter.parse("12-December-2012");
long mills = date.getTime();

看一下SimpleDateFormat類,它可以解析String並返回DateDate類的getTime方法。

現在是時候有人為這個問題提供了現代答案。 在2012年問到這個問題的時候,那些回答的答案也是很好的答案。 為什么2016年發布的答案也使用當時很久的過時類SimpleDateFormatDate對我來說有點神秘。 java.time ,現代Java日期和時間API,也稱為JSR-310,使用起來非常好。 您可以通過ThreeTenABP在Android上使用它,請參閱此問題:如何在Android項目中使用ThreeTenABP

對於大多數用途,我建議使用自UTC時間開始的紀元以來的毫秒數。 要獲得這些:

    DateTimeFormatter dateFormatter
            = DateTimeFormatter.ofPattern("d-MMMM-uuuu", Locale.ENGLISH);
    String stringDate = "12-December-2012";
    long millisecondsSinceEpoch = LocalDate.parse(stringDate, dateFormatter)
            .atStartOfDay(ZoneOffset.UTC)
            .toInstant()
            .toEpochMilli();
    System.out.println(millisecondsSinceEpoch);

這打印:

1355270400000

如果您需要在某個特定時區的某天開始時間,請指定該時區而不是UTC,例如:

            .atStartOfDay(ZoneId.of("Asia/Karachi"))

正如預期的那樣,結果略有不同:

1355252400000

還有一點需要注意,請記住為DateTimeFormatter提供一個語言環境。 我把12月份當作英語,還有其他語言,那個月被稱為相同,所以請自己選擇合適的語言環境。 如果您沒有提供語言環境,格式化程序將使用JVM的語言環境設置(在許多情況下可能有效),然后在具有不同語言環境設置的設備上運行應用程序時出現意外故障。

您可以使用simpleDateFormat來解析字符串日期。

使用simpledateformat您可以輕松實現它。

1)首先使用simpledateformatter將字符串轉換為java.Date。

2)使用getTime方法從日期獲得毫秒數

 public class test {
      public static void main(String[] args) {
      String currentDate = "01-March-2016";
      SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
     Date parseDate = f.parse(currentDate);
     long milliseconds = parseDate.getTime();
  }
        }

更多示例請單擊此處

最簡單的方法是使用Date Using Date()和getTime()

    Date dte=new Date();
    long milliSeconds = dte.getTime();
    String strLong = Long.toString(milliSeconds);
    System.out.println(milliSeconds)

試試下面的代碼

        SimpleDateFormat f = new SimpleDateFormat("your_string_format", Locale.getDefault());
        Date d = null;
        try {
            d = f.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long timeInMillis = d.getTime();

暫無
暫無

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

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