Java Dateformat - 我可以将输入与某些格式进行比较,并根据匹配的格式解析输入吗? [英] Java Dateformat -- Can I compare input to certain formats and parse the input based on the format that it is matched to?

查看:104
本文介绍了Java Dateformat - 我可以将输入与某些格式进行比较,并根据匹配的格式解析输入吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

用户可以输入01/23/1983或1/23/1983

A user can enter 01/23/1983 or 1/23/1983

如何使用DateFormat来编写两种不同类型的格式(如MM / DD / YYYY)和(M / DD / YYYY),并将它们与实际日期进行比较,以查看哪一个与日期匹配,以便成功解析

How would I use DateFormat to write up two different kinds of formats like (MM/DD/YYYY) and (M/DD/YYYY) and compare them to the actual date to see which one matches the date so I could parse it successfully?

推荐答案

由于Johan发布了一个不正确的解决方案,我觉得不得不发布正确的解决方案。 MM / dd / yyyy将格式化两个测试字符串:

Because Johan posted an incorrect solution, I feel obliged to post the correct one. "MM/dd/yyyy" will format both of your test Strings:

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

public class DateFormatTest {
   public static void main(String[] args) {
      String[] tests = {"01/23/1983", "1/23/1983", "1/3/1983"};

      String formatString = "MM/dd/yyyy";

      SimpleDateFormat sdf = new SimpleDateFormat(formatString);

      for (String test : tests) {
         Date date = null;
         try {
            date = sdf.parse(test);
         } catch (ParseException e) {
            e.printStackTrace();
         }
         System.out.println(date);
      }
   }
}

这篇关于Java Dateformat - 我可以将输入与某些格式进行比较,并根据匹配的格式解析输入吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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