Cristian Lehuede Lyon
Cristian Lehuede Lyon

Reputation: 1947

Java Gregorian calendar to specific format

I've been trying to format a gregorian calendar to a specific format as to fulfill a webservice but I don't know how to make it elegant. Right now I'm trying to format by getting the hour of minute and parsing them but it looks horrible. I need to format it as xsd:dateTime 2001-10-26T21:32:52, 2001 Any helps appreciated. Thanks!

Upvotes: 1

Views: 13737

Answers (3)

Chintan Soni
Chintan Soni

Reputation: 25267

Try this:

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

public class ConversionExamplesDate {

  // Convert from String to date
  private void stringToDate() {

    try {
      Date date1;
      date1 = new SimpleDateFormat("MM/dd/yy").parse("05/18/05");
      System.out.println(date1);
      Date date2 = new SimpleDateFormat("MM/dd/yyyy").parse("05/18/2007");
      System.out.println(date2);
    } catch (ParseException e) {
      e.printStackTrace();
    }
  }

  // Convert from millisecs to a String with a defined format
  private void calcDate(long millisecs) {
    SimpleDateFormat date_format = new SimpleDateFormat("MMM dd,yyyy HH:mm");
    Date resultdate = new Date(millisecs);
    System.out.println(date_format.format(resultdate));
  }

  private void writeActualDate(){
    Calendar cal = new GregorianCalendar();
    Date creationDate = cal.getTime();
    SimpleDateFormat date_format = new SimpleDateFormat("MMM dd,yyyy HH:mm");
    System.out.println(date_format.format(creationDate));
  }


  public static void main(String[] args) {
    ConversionExamplesDate convert = new ConversionExamplesDate();
    convert.stringToDate();
    convert.calcDate(System.currentTimeMillis());
    convert.writeActualDate();
  }
} 

Upvotes: 1

Micho Rizo
Micho Rizo

Reputation: 1092

Should be straight foward to adjust the format to what you need ... this produces "2013-06-08T20:56:25Z"

SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
timeFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
String time = timeFormat.format(new Date());

Upvotes: 4

hd1
hd1

Reputation: 34657

Using joda:

DateTime dt = new DateTime();
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
String str = fmt.print(dt);

Upvotes: 0

Related Questions