格式显示日期dd / MM / yyyy

时间:2018-01-24 10:45:43

标签: android date datetime simpledateformat

我有一种方法来格式化从服务器获取的日期格式2018-01-18T13:52:49.107Z。我想将此格式转换为仅显示日,月和年,但它不起作用。如何从服务器转换此响应以显示日期格式。

这是我的方法:

private String formatDate(String dateString) {
    try {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss.S" );
        Date d = sd.parse(dateString);
        sd = new SimpleDateFormat("dd/MM/yyyy");
        return sd.format(d);
    } catch (ParseException e) {
    }
    return "";
}

7 个答案:

答案 0 :(得分:2)

尝试使用yyyy-MM-dd'T'HH:mm:ss.SSS

更改日期格式
private String formatDate(String dateString) {
    try {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS" );
        Date d = sd.parse(dateString);
        sd = new SimpleDateFormat("dd/MM/yyyy");
        return sd.format(d);
    } catch (ParseException e) {
    }
    return "";
}

答案 1 :(得分:2)

请使用此

SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" );

答案 2 :(得分:1)

试试这个

 private String formatDate(String dateString) {

    SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    SimpleDateFormat output = new SimpleDateFormat("dd/MM/yyyy");

    Date d = null;
    try {
        d = input.parse(dateString);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    String formatted = output.format(d);
    Log.i("DATE", "" + formatted);


    return formatted;
}

<强>输出

enter image description here

答案 3 :(得分:0)

将输入字符串转换为日期

DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
    Date date = inputFormat.parse(inputString);

将日期格式化为输出格式

DateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
    String outputString = outputFormat.format(date);

答案 4 :(得分:0)

以下是实现此目的的代码:

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;



public class VirtualKeyBoard extends Robot
{

    public VirtualKeyBoard() throws AWTException
    {
        super();
    }

    public void pressKeys(String keysCombination) throws IllegalArgumentException
    {
            for (String key : keysCombination.split("\\+"))
            {
                try
                {   System.out.println(key);
                    this.keyPress((int) KeyEvent.class.getField("VK_" + key.toUpperCase()).getInt(null));

                } catch (IllegalAccessException e)
                {
                    e.printStackTrace();

                }catch(NoSuchFieldException e )
                {
                    throw new IllegalArgumentException(key.toUpperCase()+" is invalid key\n"+"VK_"+key.toUpperCase() + " is not defined in java.awt.event.KeyEvent");
                }


            }


    }


    public void releaseKeys(String keysConbination) throws IllegalArgumentException
    {

            for (String key : keysConbination.split("\\+"))
            {
                try
                { // KeyRelease method inherited from java.awt.Robot
                    this.keyRelease((int) KeyEvent.class.getField("VK_" + key.toUpperCase()).getInt(null));
                } catch (IllegalAccessException e)
                {
                    e.printStackTrace();
                }catch(NoSuchFieldException e )
                {
                    throw new IllegalArgumentException(key.toUpperCase()+" is invalid key\n"+"VK_"+key.toUpperCase() + " is not defined in java.awt.event.KeyEvent");
                }
            }


    }

    public static void main(String[] args) throws AWTException
    {


         VirtualKeyBoard kb = new VirtualKeyBoard();


         String keyCombination = "control+a"; // select all text on screen
         //String keyCombination = "shift+a+1+c"; // types A!C on screen

         // For your case 
         //String keyCombination = "alt+1+2+3";


         kb.pressKeys(keyCombination);
         kb.releaseKeys(keyCombination); 



    }


}

输出=格式= 2018/01/18

答案 5 :(得分:0)

这是ISO-DATE时间格式。 可以使用添加的小时,分​​钟和秒(YYYY-MM-DDTHH:MM:SSZ)

来编写ISO日期

日期和时间用大写字母T分隔。

UTC时间定义为大写字母Z。

private String formatDate(String dateString) {
    try {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ" );
        Date d = sd.parse(dateString);
        sd = new SimpleDateFormat("dd/MM/yyyy");
        return sd.format(d);
    } catch (ParseException e) {
    }
    return "";
}

答案 6 :(得分:0)

TL:DR

private static final DateTimeFormatter dateFormatter
        = DateTimeFormatter.ofPattern("dd/MM/yyyy");

private static String formatDate(String dateString) {
    return Instant.parse(dateString)
            .atZone(ZoneId.of("Pacific/Tarawa"))
            .format(dateFormatter);
}

您需要指定时区

根据您的字符串2018-01-18T13:52:49.107Z,上述方法会返回19/01/2018。的 19 ?是的,当它是UTC时间13:52时,它已经是塔拉瓦环礁的第二天了。由于它在地球上的任何地方都不是同一个日期,因此您需要指定日期所在的时区。如果不是太平洋/塔拉瓦,请替换您想要的时区。例如非洲/马普托或亚洲/萨哈林。然后,您将获得该区域中的日期,格式为指定。它并不总是与字符串中的日期一致(在本例中为2018年1月18日),因为字符串以UTC表示日期和时间。要使用用户的时区,您可以尝试指定ZoneId.systemDefault()。这将使用JVM的时区设置。请注意它很脆弱,您可以在程序的其他部分或同一JVM中运行的其他程序下更改设置。如果 打算以字符串形式显示UTC中的日期,请使用:

    return Instant.parse(dateString)
            .atOffset(ZoneOffset.UTC)
            .format(dateFormatter);

现在结果保证为18/01/2018

java.time

我使用的是现代Java日期和时间API java.time。我建议你这样做。 Date类已经过时了,SimpleDateFormat不仅如此,它也是出了名的麻烦。现代API可以更好地使用。

问题:我可以在Android上使用java.time吗?

是的,您可以在Android上使用java.time。它只需要至少Java 6

  • 在Java 8及更高版本和更新的Android设备上,内置了现代API。
  • 在Java 6和7中获取ThreeTen Backport,新类的后端端口(适用于JSR 310的ThreeTen;请参阅底部的链接)。
  • 在较旧的Android上使用Android版的ThreeTen Backport。它被称为ThreeTenABP。并确保使用子包从org.threeten.bp导入日期和时间类。

您的代码出了什么问题?

您的方法中的主要错误(使用过时的类更糟糕)是在以下两行之间!

    } catch (ParseException e) {
    }

空的catch阻止吞噬异常,这样您就无法查看出现了什么问题。永远不要那样做。试试例如:

    } catch (ParseException e) {
        System.out.println("Message:      " + e.getMessage());
        System.out.println("Error offset: " + e.getErrorOffset());
        if (e.getErrorOffset() != -1) {
            System.out.println("Error text:   " + dateString.substring(e.getErrorOffset()));
        }
    }

打印:

Message:      Unparseable date: "2018-01-18T13:52:49.107Z"
Error offset: 5
Error text:   01-18T13:52:49.107Z

因此,您的格式化程序无法解析月份01。检查the documentation,它说的是月份:“如果模式字母的数量是3或更多,则将月份解释为文本; ......”。因此,让我们在格式模式字符串中尝试MM而不是MMM。现在我们得到:

Message:      Unparseable date: "2018-01-18T13:52:49.107Z"
Error offset: 10
Error text:   T13:52:49.107Z

T是冒犯的。当然,它不在模式字符串中。要指示文字是格式的一部分,请将其括起来:yyyy-MM-dd'T'HH:mm:ss.S。下次您的方法返回时:

18/01/2018

我们通过了吗?我不会说。你最后忽略了Z。它表示从UTC或“祖鲁时区”偏移0。通过忽略它,您将日期时间字符串解析为JVM默认时区中的日期时间,这会给出不正确的时间。在较新的Java版本中,可以使用格式模式字母大写Z来解析X,其中包括一个,两个或三个。试试yyyy-MM-dd'T'HH:mm:ss.SXXX

Message:      Unparseable date: "2018-01-18T13:52:49.107Z"
Error offset: 22
Error text:   7Z

似乎一个S匹配两个数字10,但不匹配第三个小数,7。我不知道为什么,但让我们放三个小数SSSyyyy-MM-dd'T'HH:mm:ss.SSSXXX。现在它有效。

链接