在andorid中将字符串转换为日期格式 [英] Convert String to Date format in andorid

查看:85
本文介绍了在andorid中将字符串转换为日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到像 1604341549 这样的字符串,并想将它们转换为普通的日期格式,如2012 年 2 月 12 日 4:00.这是我的实现

I am getting the strings like 1604341549 and want to convert them to normal date format like 12 feb 2012 4:00. Here is my implementation

 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            Date d = sdf.parse(date);
            sdf.applyPattern("dd MMM yyyy hh:mm");
            holder.v.setText(sdf.format(d));
        } catch (ParseException ex) {
            Log.e("Exception", ex.getLocalizedMessage());
        }

我检查了日志,它在 try 块之前将日期显示为字符串,但它没有在 try 块中实现,而是给出了一个错误;无法解析的日期:1604341549"".

I have checked the logs and it is showing the dates as String before the try block but it is not implementing in the try block instead it is giving an error " Unparseable date: "1604341549" ".

推荐答案

java.time through desugaring

考虑使用 java.time,现代 Java 日期和时间 API,用于您的日期和时间工作.让我们首先声明两个格式化程序,一个用于您的输入,一个用于您想要的输出.

java.time through desugaring

Consider using java.time, the modern Java date and time API, for your date and time work. Let’s first declare two formatters, one for your input and one for your desired output.

/** For parsing seconds since the epoch */
private static final DateTimeFormatter unixTimestampFormatter
        = new DateTimeFormatterBuilder()
                .appendValue(ChronoField.INSTANT_SECONDS)
                .toFormatter();

/** For formatting into normal date and time */
private static final DateTimeFormatter normalFormatter
        = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
                .withLocale(Locale.UK);

现在转换是这样的:

    String inputStr = "1604341549";
    Instant inst = unixTimestampFormatter.parse(inputStr, Instant.FROM);
    String normalDateTimeStr = inst.atZone(ZoneId.systemDefault())
            .format(normalFormatter);
    System.out.println(normalDateTimeStr);

输出为:

2020 年 11 月 2 日 19:25:49

02-Nov-2020 19:25:49

我确信 Shamm 在另一个答案中是正确的:您的输入字符串包含所谓的 Unix 时间戳,即自 Unix 纪元1970 年 1 月 1 日 00:00 UTC.使用 java.time 我们可以构建一个解析这样的格式化程序.

I am convinced that Shamm is correct in the other answer: your input strings contain so-called Unix timestamps, that is, counts of seconds since the Unix epoch on Jan 1, 1970 at 00:00 UTC. With java.time we can build a formatter that parses such.

为了提供正常"输出,我使用了 Java 的内置日期和时间格式.在这种情况下适用于英国语言环境,但您应该对大多数内容用户使用您用户的语言环境.

For giving "normal" output I am using Java’s built-in date and time format. In this case for UK locale, but you should use your users’ locale for most content users.

首先,您试图将输入字符串解析为包含年、月、日、小时等,但它没有.所以你很幸运地得到了一个异常,所以你意识到它是错误的(SimpleDateFormat 通常不会给出那个,让你相信一切都很好,但事实并非如此).

First, you were trying to parse the input string as containing year, month, date, hour, etc., which it didn’t. So you were lucky to get an exception so you got aware that it’s wrong (SimpleDateFormat very often does not give that, leaving you believing that everything is fine when it isn’t).

SimpleDateFormat 将 1604 解析为年,将 34 解析为月,将 15 解析为月中的某一天,将 49 解析为一天中的小时.然后它反对,因为分钟(和秒)没有任何数字.

SimpleDateFormat parsed 1604 as year, 34 as month, 15 as day of month and 49 as hour of day. It then objected because there weren’t any digits left for the minutes (and seconds).

java.time 在较旧和较新的 Android 设备上都能很好地工作.它只需要至少 Java 6.

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • 在 Java 8 及更高版本以及更新的 Android 设备(从 API 级别 26 开始)中,内置了现代 API.
  • 在非 Android Java 6 和 7 中获得 ThreeTen Backport,现代类的向后移植(ThreeTen for JSR 310;请参阅底部的链接).
  • 在较旧的 Android 上,使用脱糖或 ThreeTen Backport 的 Android 版本.它被称为 ThreeTenABP.在后一种情况下,请确保使用子包从 org.threeten.bp 导入日期和时间类.
  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.
  • Oracle tutorial: Date Time explaining how to use java.time.
  • Unix time
  • Java Specification Request (JSR) 310, where java.time was first described.
  • ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
  • Java 8+ APIs available through desugaring
  • ThreeTenABP, Android edition of ThreeTen Backport
  • Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

这篇关于在andorid中将字符串转换为日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆