当前位置: 动力学知识库 > 问答 > 编程问答 >

java - SimpleDateFormat - Do you need to use RegEx?

问题描述:

I have the code below, which produces this:

2012-07-28 17:30:23

Which is what I want. But if I want to extract all the numbers on their own to assign to variables, do I need to make a RegEx or is there some way to simply extract these from the SimpleDateFormat?

 SimpleDateFormat dateFormatUCT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

dateFormatUCT.setTimeZone(TimeZone.getTimeZone("UCT"));

//Time in UCT

String date = dateFormatUCT.format(new Date());

System.out.println(date);

网友答案:

You have a Date. Convert if to a GregorianCalendar, and ask every field to the GregorianCalendar:

GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("UCT")); // or UTC?
cal.setTime(theDate); // if you want something other than the current date
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1; // months start at 0, duh!
...
网友答案:

You don't need a regex. You just take the Date and give it to a Calendar, then use the get() method to get each of the fields.

Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.setTime(new Date());

System.out.println(c.get(Calendar.YEAR));
System.out.println(c.get(Calendar.MONTH));
System.out.println(c.get(Calendar.DATE));

etc.

网友答案:

1. Use split() method

2. Do it like this...

String s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

  String[] arr = s.split(" ");

  String newDStr = arr[0];

  String newTStr = arr[1];

  String[] DateArr = newDStr.split("-");       // Holds Date values.
  String[] TimeArr = newTStr.split(":");       // Holds Time values
网友答案:

You cannot extract them from SimpleDateFormat afaik, but you could use Java.util.Calendar to extract the date components using its get(Calendar.{DAY_OF_MONTH|MONTH|YEAR|HOUR|MINUTE|SECOND}) method. The Calendar object provides a setTime() method that takes a date. So, you could use the same date to format using SimpleDateFormat and to extract date components using the Calendar.

分享给朋友:
您可能感兴趣的文章:
随机阅读: