简体   繁体   English

在android中将字符串转换为日期格式

[英]Convert string to date format in android

I'm trying to convert string to date format.I trying lot of ways to do that.But not successful.我正在尝试将字符串转换为日期格式。我尝试了很多方法来做到这一点。但没有成功。 my string is "Jan 17, 2012".我的字符串是“2012 年 1 月 17 日”。 I want to convert this as " 2011-10-17".我想将其转换为“2011-10-17”。 Could someone please tell me the way to do this?有人可以告诉我这样做的方法吗? If you have any worked through examples, that would be a real help!如果您有任何已完成的示例,那将是真正的帮助!

try {

     String strDate = "Jan 17, 2012";

     //current date format
     SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy");

     Date objDate = dateFormat.parse(strDate);

     //Expected date format
     SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");

     String finalDate = dateFormat2.format(objDate);

     Log.d("Date Format:", "Final Date:"+finalDate)

   } catch (Exception e) {
      e.printStackTrace();
 }
   String format = "yyyy-MM-dd";
   SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
   System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
   sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
   System.err.format("%30s %s\n", format, sdf.format(new Date(0)));

Which produces this output when run in the PDT time zone:在 PDT 时区运行时会产生此输出:

                 yyyy-MM-dd 1969-12-31
                 yyyy-MM-dd 1970-01-01

For more info look at here欲了解更多信息,请看这里

I suggest using Joda Time , it's the best and simplest library for date / dateTime manipulations in Java, and it's ThreadSafe (as opposed to the default formatting classes in Java).我建议使用Joda Time ,它是 Java 中最好和最简单的日期/日期时间操作库,它是 ThreadSafe(与 Java 中的默认格式类相反)。

You use it this way:你这样使用它:

// Define formatters:
DateTimeFormatter inputFormat = DateTimeFormat.forPattern("MMM dd, yyyy");
DateTimeFormatter outputFormat = DateTimeFormat.forPattern("yyyy-MM-dd");

// Do your conversion:
String inputDate = "Jan 17, 2012";
DateTime date = inputFormat.parseDateTime(inputDate);
String outputDate = outputFormat.print(date);
// or:
String outputDate = date.toString(outputFormat);
// or:
String outputDate = date.toString("yyyy-MM-dd");

// Result: 2012-01-17

It also provides plenty of useful methods for operations on dates (add day, time difference, etc.).它还提供了大量有用的日期操作方法(添加日期、时差等)。 And it provides interfaces to most of the classes for easy testability and dependency injection.并且它提供了大多数类的接口,以便于测试和依赖注入。

public static Date getDateFromString(String date) {

    Date dt = null;

    if (date != null) {
        for (String sdf : supportedDateFormats) {
            try {
                dt = new Date(new SimpleDateFormat(sdf).parse(date).getTime());
                break;
            } catch (ParseException pe) {
                pe.printStackTrace();
            }
        }
    }
    return dt;
}

Why do you want to convert string to string try to convert current time in milisecond to formated String, this method will convert your milisconds to a data formate.为什么要将字符串转换为字符串尝试将当前时间以毫秒为单位转换为格式化字符串,此方法会将您的毫秒转换为数据格式。

 public static String getTime(long milliseconds)
{

         return DateFormat.format("MMM dd, yyyy", milliseconds).toString();
}

you can also try DATE FORMATE class for better understanding.您也可以尝试DATE FORMATE类以更好地理解。

You can't convert date from one format to other. while you are taking the date take you have take the date which ever format the you want. If you want the date in yyyy-mm-dd. You can get this by using following way.

            java.util.Calendar calc = java.util.Calendar.getInstance();

        int day = calc.get(java.util.Calendar.DATE);
        int month = calc.get(java.util.Calendar.MONTH)+1;
        int year = calc.get(java.util.Calendar.YEAR);

           String currentdate = year +"/"+month +"/"+day ;

Try this simple method:试试这个简单的方法:

        fun getFormattedDate(strDate:String): String {
        try {
            val dateFormat = SimpleDateFormat("dd/mm/yyyy")//old format
            val dateFormat2 = SimpleDateFormat("mm/dd/yyyy")//require new formate
            val objDate = dateFormat.parse(strDate)
            return dateFormat2.format(objDate)
        } catch (e:Exception) {
            return ""
        }
    }

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

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