简体   繁体   English

android将字符串转换为日期格式,再转换回字符串

[英]android convert a string to a date format the convert back to string

What i'm wanting to do is format the string 08-18 15:00 to read 18-08-12 15:00 . 我想要做的是将字符串08-18 15:00格式化为18-08-12 15:00 How do I convert it into a date format it and the convert back to a string so i can use to setText to a textview? 我如何将其转换为日期格式并将其转换回字符串,以便可以将setText转换为textview?

This is what you are looking for. 这就是您要寻找的。 You have to use SimpleDateFormat . 您必须使用SimpleDateFormat Here is the link: String to date conversion 这里是链接: 字符串到日期的转换

Of course, using SimpleDateFormat would be better solution, but if you insist and if you know coming style... Then you can simply format it yourself, with some codes like this: 当然,使用SimpleDateFormat会是更好的解决方案,但是如果您坚持要求并且知道即将到来的样式...那么您可以使用以下代码自行格式化自己:

public static String ConvertDate(String valueToFormat) {
      String value = valueToFormat;
      String day = value.substring(value.indexOf("-") + 1, value.indexOf(" "));
      String month = value.substring(0, value.indexOf("-"));
      String time = value.substring(value.indexOf(" ") + 1, value.lenght());

      Calendar c = Calendar.getInstance();
      int year = c.get(Calendar.YEAR);

      // if you want year to appear as only last two items
      year = year % 100;

      value = day + "-" + month + "-" + year + " " + time;
      return value;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM