免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1255 | 回复: 0
打印 上一主题 下一主题

Cast String to Date in Java [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-04-07 15:12 |只看该作者 |倒序浏览

                There is a case that if we use String to save Date value and we need to sort by Date, then we need to cast Strng to Date and then compare them. And depending on different format of the string date like mm/dd/yy, or dd/mm/yy, or dd/mm/yyyy, or mm/dd/yyyy. we need to parse all the different format to the same date.

Thanks to the API DateFormat, we can do it very easily

Like if we want to parse mm/dd/yyyy, as we know that this is the date format for english.

The following code can do this job


        try {
     
     DateFormat formatter = new SimpleDateFormat("MM/dd/yy",Locale.ENGLISH);
     Date date = (Date)formatter.parse("04/29/02");
     Date date2 = (Date)formatter.parse("01/02/03");
     
     System.out.println(date.getTime()+"\t"+ date.toString());
     System.out.println(date2.getTime()+"\t"+ date2.toString());
     long long1 = date.getTime();
     long long2=date2.getTime();
     System.out.println(new Date(long1) + "\t"+ new Date(long2));
     
     } catch (ParseException e) {
     }

               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/2956/showart_272683.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP