How to format a date android?

2019-07-31 16:37发布

I have a date in String an I using this:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
dataUltima = sdf.format(sdf);

to format the date. But this method return the actual date of system. How can I only format the date without change the date.

Obs. I'm getting this date from a server, it come to me yyy-dd-MM and I want it dd/MM/yyyy

4条回答
手持菜刀,她持情操
2楼-- · 2019-07-31 16:46

I am not sure what is your problem.

Try it. Maybe help.

String server_format = "2013-01-02";    //server comes format ?
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {

    Date date = sdf.parse(server_format);
    System.out.println(date);
    String your_format = new SimpleDateFormat("dd/MM/yyyy").format(date);
    System.out.println(your_format);    //you want format ?

} catch (ParseException e) {
    System.out.println(e.toString()); //date format error
}
查看更多
家丑人穷心不美
3楼-- · 2019-07-31 16:48

Ty following:

try
{
  //create SimpleDateFormat object with source string date format
  SimpleDateFormat sdfSource = new SimpleDateFormat("yyy-dd-MM");

  //parse the original date string(strDate) that you are getting from server into Date object
  Date date = sdfSource.parse(strDate);

  //create SimpleDateFormat object with desired date format
  SimpleDateFormat sdfDestination = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");

  //parse the date into another format
  strDate = sdfDestination.format(date);

  System.out.println("Date is converted");
  System.out.println("Converted date is : " + strDate);

}
catch(ParseException pe)
{
  System.out.println("Parse Exception : " + pe);
}

Source: Convert date string from one format to another format using SimpleDateFormat

Hope this helps.

查看更多
对你真心纯属浪费
4楼-- · 2019-07-31 16:58

Try this code:

    Date newDate = new Date();

    // Print the date with the server format
    SimpleDateFormat sdfServer = new SimpleDateFormat("yyy-dd-MM ");
    System.out.println("Server date " + sdfServer.format(newDate));

    // Create a new formatter to get the date in the format you want
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
    String dataUltima = sdf.format(newDate);
    System.out.println("System date " + dataUltima);
查看更多
劳资没心,怎么记你
5楼-- · 2019-07-31 17:03

Try this:

String date = "2011-11-12 11:11:11"; //Fill with sample date received from server
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-dd-MM HH:mm:ss");
Date testDate = null;
try {
    testDate = sdf.parse(date);
}catch(Exception ex){
    ex.printStackTrace();
}
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm");
String dataUltima = formatter.format(testDate);
System.out.println("Date is "+dataUltima );
查看更多
登录 后发表回答