0

After parsing JSON UTC date-time data from a server, I was presented with

2017-03-27 16:27:45.567

... is there any way to format this without using tedious amount of String manipulation so that the seconds part is rounded up to 46 prior to passing it in as a DateTimeFormat pattern of say, "yyyy-MM-dd HH:mm:ss"?

DaveNOTDavid
  • 1,753
  • 5
  • 19
  • 37

2 Answers2

1

You can round the second up like this:

DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS")
        .withZoneUTC()
        .parseDateTime("2017-03-27 16:27:45.567")
        .secondOfMinute()
        .roundCeilingCopy();

System.out.println(dateTime);
// 2017-03-27T16:27:46.000Z
shmosel
  • 49,289
  • 6
  • 73
  • 138
0

Have you looked at (and could you use) the MomentJS library? I had issues with reading various date formats from the server and making sense of them in JavaScript code (which led me here). Since then, I've used MomentJS and working with dates/times in JavaScript has been much easier.

Here is an example:

<script>
    try
    {
        var myDateString = "2017-03-27 16:27:45.567";
        var d = moment(myDateString);

        var result = d.format('YYYY/MM/DD HH:mm:ss');
        alert("Simple Format: " + result);

        // If we have millliseconds, increment to the next second so that 
        // we can then get its 'floor' by using the startOf() function.
        if(d.millisecond() > 0)
            d = d.add(1, 'second');

        result = d.startOf('second').format('YYYY/MM/DD HH:mm:ss');
        alert("Rounded Format: " + result);
    }
    catch(er)
    {
        console.log(er);
    }
</script>

But of course, you'll probably want to wrap this logic into a function.

Community
  • 1
  • 1
MJS
  • 71
  • 6