How to format a date android?

社会主义新天地 提交于 2019-12-11 07:48:10

问题


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


回答1:


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
}



回答2:


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.




回答3:


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);



回答4:


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 );


来源:https://stackoverflow.com/questions/17683097/how-to-format-a-date-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!