简体   繁体   English

在Java中将字符串转换为日期

[英]converting a string to date in Java

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TesterA
{
    public static void main(String[] args)
    {
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
        String dateInString = "7-Jun-2013";

        try
        {
            Date date = formatter.parse(dateInString);
            System.out.println(date);
            System.out.println(formatter.format(date));
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }
    }
}

I was trying to run this sample code copy from a web, but it doesn't work. 我试图从网络上运行此示例代码副本,但是它不起作用。 How should I change it? 我该如何更改?

This is the error I got 这是我得到的错误

java.text.ParseException: Unparseable date: "7-Jun-2013"
    at java.text.DateFormat.parse(DateFormat.java:366)
    at TesterA.main(TesterA.java:14)

I think it is a problem with your locale. 我认为您的语言环境存在问题。

Try: 尝试:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);

java.text.ParseException means you provided a string which cannot be parsed using the current settings. java.text.ParseException表示您提供了无法使用当前设置进行解析的字符串。

Just set the Locale . 只需设置Locale

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);

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

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