【问题标题】:Convert string "11-10-10 12:00:00" into Date object [duplicate]将字符串“11-10-10 12:00:00”转换为日期对象[重复]
【发布时间】:2011-06-02 20:46:16
【问题描述】:

可能重复:
how to parse date in java?

我想将字符串"11-10-10 12:00:00" 转换为Date 对象,但我不能这样做。你能帮帮我吗?

我有一个 Date 对象,其值为“Mon Oct 11 00:00:00 IST 2010”

DateFormat newDateFormat = new SimpleDateFormat("dd-MM-yy hh:mm:ss");    
String strDate = newDateFormat.format(tempDate);  
//**i got strDate as strDate is : 11-10-10 12:00:00**
DateFormat newDateFormat1 = new SimpleDateFormat("dd-MM-yy hh:mm:ss");    
try {    
 tempDate = newDateFormat1.parse(strDate); 
     // **getting tempDate as - Mon Oct 11 00:00:00 IST 2010**    
   } catch (ParseException e) {    
 // TODO Auto-generated catch block    
 e.printStackTrace();    
 }

【问题讨论】:

  • 什么语言 - 看起来像 C#。这也被问过很多次了。查看“相关”下的问题 ->

标签: java date-format simpledateformat


【解决方案1】:
DateFormat newDateFormat = new SimpleDateFormat("dd-MM-yy HH:mm:ss");    
Date d = newDateFormat.parse("11-10-10 12:00:00");
System.out.println(d);

这里是ideone demo

【讨论】:

  • 嗨希拉尔,感谢您的回复。但是您的代码会产生相同的输出。 d= "Mon Oct 11 12:00:00 IST 2010" 我想要 "dd-MM-yy HH:mm:ss" 格式。
  • 此代码会按照您的要求解析日期。打印它是另一个问题。日期只是一个数字,日期和格式彼此无关,所以 Java 会随心所欲地打印日期。
【解决方案2】:

我认为这是 Java 代码——不是我的专长——但我认为您的问题是格式字符串中的“hh”,这导致 parse 解释为“12:00:00”作为午夜而不是中午。尝试将其更改为“HH”,看看是否正确解析。

【讨论】:

  • 你好,Dan Tao,我也尝试过 HH,但它不起作用。
【解决方案3】:

对于印地语,您需要使用 CultureInfo,它是“hi-IN”。有关文化的完整列表,请查看此链接 CultureInfo

    class Program
{
    static void Main(string[] args)
    {
        var str = "11-10-10 12:00:00";

        DateTime dateTime = DateTime.Parse(str, new CultureInfo("hi-IN", false));
    }
}

【讨论】:

  • 嗨,弗拉德,感谢您的回复,但该代码似乎适用于微软,而我的问题适用于 JAVA。
猜你喜欢
  • 2021-03-30
  • 2016-04-14
  • 2022-01-10
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 2021-07-10
  • 2013-11-01
相关资源
最近更新 更多