开发者

How to break apart a string value and re-arrange characters

开发者 https://www.devze.com 2023-04-08 12:34 出处:网络
So from what I have found I would have to write a swap method?Only problem is from the codes I have been looking over it is a bit over my head.

So from what I have found I would have to write a swap method? Only problem is from the codes I have been looking over it is a bit over my head.

I am getting a value from a xml file, for example "20120411" What I would like it to be once passed to another string is April 11, 2012, or at least 04/11/12. I have found simple ways to do this in just about every other language besides java. If its 开发者_如何学JAVAsimple enough for someone to show me the code to accomplish this, or point me in the right direction I would appreciate it!


Look at using a SimpleDateFormat object. There are many many examples of how to use this in this forum, and so a little searching will bring you riches. If you look this over and still are stuck, then you should consider showing us your attempt and tell us what's not working for you, and we'll likely be able to easily help you.

A format String to try includes "yyyyMMdd". You'd construct your SDF object with this String, parse the xml String and thereby turn it into a Date object. You'd use a second SDF object with a different pattern String, perhaps "MMMM dd, yyyy" to format the Date into a different String. Again, give it a try!

e.g.,

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

public class SdfTest {
   public static void main(String[] args) {
      SimpleDateFormat sdfInput = new SimpleDateFormat("yyyyMMdd");
      SimpleDateFormat sdfOutput = new SimpleDateFormat("MMMM dd, yyyy");

      try {
         Date date = sdfInput.parse("20120411");
         String output = sdfOutput.format(date);
         System.out.println(output);

      } catch (ParseException e) {
         e.printStackTrace();
      }
   }
}


This takes "20080105" and returns "01/05/2008".

StringBuffer b = new StringBuffer(dateStr);
b.append(b.substring(0, 4)).delete(0, 4); // put year at end
b.insert(2, "/");
b.insert(5, "/");


If all you want to do it rearrange characters you can do a replace:

 String dateString = "20120411".replaceAll("\\d{2}(\\d{2})(\\d{2})(\\d{2})", "$2/$3/$1");  // outputs: 04/11/12
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号