0

I'm trying to do some simple client side date manipulation in Java. It's stored in UTC down to the millisecond, but for client side display I would like to truncate it to the second and display it in PST.

Currently, I'm getting the time from the db as a string like so:

    myDataSet.someDate = resultSet.getString("some_date"));

I was thinking that I get some sort of Time object, manipulate it so it displays in the format I want and then wrap it in a string for display purposes. Here's what I have so far.

    myDataSet.someDate = String.valueOf(resultSet.getTimestamp("some_date"));

This gets me the string, but the time is not in the correct form. I've found a few answers, but they all seem to want me to write another function. This seems like something I should be able to do in one line of code.

BarFooBar
  • 1,086
  • 2
  • 13
  • 32
  • 3
    See [`SimpleDateFormat`](http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html) and any [example usage](http://stackoverflow.com/questions/9872419/converting-string-to-date-using-simpledateformat). – maerics May 27 '14 at 18:16

3 Answers3

1

The following code takes a Calendar object, makes a Date object out of it, and formats it into a readable String.

Calendar cal = new GregorianCalendar();
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
Date s = new Date(cal.getTimeInMillis());
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy");
String formatted = sdf.format(s);

This returns something like:
Tue, May 27, 2014

unknown
  • 4,859
  • 10
  • 44
  • 62
Jordan.J.D
  • 7,999
  • 11
  • 48
  • 78
0

Date formatting in Java is a terrible pain, so it is unlikely that you will find a one-liner. However, you should be able to use a SimpleDateFormat like so (untested):

String format = "yyyy-MM-dd HH:mm z"; // <-- change as needed
DateFormat formatter = new SimpleDateFormat(format);
Timestamp timestamp = resultSet.getTimestamp("some_date");
String dateString = formatter.format(new java.util.Date(timestamp.getTime()));
maerics
  • 151,642
  • 46
  • 269
  • 291
0

I decided to use Joda-Time. It seemed to offer more complete functionality than anything native.

DateTime date = DateTime.parse(myDataSet.getString("some_date"), DateTimeFormat.forPattern("yy-MM-dd HH:mm:ss.SSS"));
myDataSet.someDate = date.toString("dd-MMM-yy HH:mm:ss");

This converts my string to a Joda DateTime object and then reformats it. Still working on a good way to convert UTC to PST while accounting for offset besides .minusHours, but it seems like the functionality is there.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
BarFooBar
  • 1,086
  • 2
  • 13
  • 32