本文共 932 字,大约阅读时间需要 3 分钟。
为了将日期字符串"2018-03-04"格式化为"2018年03月04日",我们可以使用SimpleDateFormat类进行解析和格式化操作。抽取要点如下:
解析日期字符串:
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
格式化日期对象:
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日");
注意事项:
import java.text.SimpleDateFormat;import java.util.Date;public class Test { public static void main(String[] args) throws ParseException { String strDate = "2018-03-04"; // 创建解析日期的SimpleDateFormat对象 SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); Date date = sdf1.parse(strDate); // 创建格式化日期的SimpleDateFormat对象,并使用中文环境 SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA); strDate = sdf2.format(date); System.out.println(strDate); }}
这个实现确保了日期正确转换,并考虑了环境设置,确保输出符合预期。
转载地址:http://idtaz.baihongyu.com/