字符串到Java的日期 [英] String to Date in Java

查看:136
本文介绍了字符串到Java的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HI,

我正在将字符串转换为日期格式。但是它返回错误的日期。例如,

I am converting String to Date format. But it returns wrong dates. for example,

String startDate = "08-05-2010"; //  (MM/dd/yyyy)

我想将其转换为Date对象,05-JUL-10

I want to convert this to "Date" object like this, 05-JUL-10

如何做?我尝试这样

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy");
scal1.setTime(dateFormat.parse((startDate)));

但我得到不可稀释的日期:。

but i am getting "Unparseable date:" .

推荐答案

如果要将一种格式的日期字符串转换为另一种格式,可以使用格式()和parse()方法 SimpleDateFormat class

If you want to convert a date string of one format to another format, you can use format() and parse() methods of SimpleDateFormat class

首先,您需要使用parse()方法将字符串解析为日期对象,设置源模式,然后使用设置目标模式的format()方法格式化日期对象:

First you need to parse the string to a date object using parse() method setting the source pattern and then format the date object using format() method setting the target pattern:

SimpleDateFormat sourceFormat = new SimpleDateFormat("MM-dd-yyyy");
Date sourceFormatDate = sourceFormat.parse("08-05-2010");
SimpleDateFormat destFormat = new SimpleDateFormat("dd-MMM-yy");
String destFormatDateString = destFormat.format(sourceFormatDate);
System.out.println(destFormatDateString); // 05-Aug-10

这篇关于字符串到Java的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆