0

Microsoft uses a datetime format that looks like this: \/Date(1399017480000-0000)\/

I would like to write a Java method that converts a Java date to Microsoft's datetime format. Can anyone point to a resource that explains how to do this?

Sandah Aung
  • 6,156
  • 15
  • 56
  • 98

1 Answers1

3

Assuming you're just talking about java.util.Date, it's as simple as:

public static String toJson(Date date) {
    return "\\/Date(" + date.getTime() + "-0000)\\/";
}

(That's assuming the backslashes should really be part of the string... it's not clear whether you actually want them or not, but you can remove them easily enough.)

Basically the first part of the string is just the number of milliseconds since the Unix epoch, which is the value in a java.util.Date as well, as accessed via getTime().

The "0000" bit is a UTC offset, but as a java.util.Date has no concept of a time zone or an offset, you can just use 0000 and you'll end up representing the right instant in time. If you were starting with a java.util.Calendar value you could convert the offset as well, if you really wanted to.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks a lot for your answer. I know Java doesn't have the notion of a TimeZone but do you mean I don't have to care about the timezone when I am posting dates to the ASP.Net server? – Sandah Aung May 01 '14 at 14:09
  • @SandahAung: Java *does* have the notion of a time zone (look at `java.util.TimeZone`; it's just that `java.util.Date` doesn't. As for whether or not you need to worry about time zones - that's very context-sensitive. Does the time zone matter for the data you're posting? – Jon Skeet May 01 '14 at 14:12
  • Yes. That's what I meant. Java's date doesn't. It looks like the server finds it useful to know the client's correct timezone since it can use that information to perform certain tasks such as send alerts at the appropriate time. – Sandah Aung May 01 '14 at 14:23
  • `Date` is very old; Java has much better date-related classes now.  If you want to be aware of timezones, an [`Instant`](https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html) would probably be more suitable.  (Or if not, a [`LocalDateTime`](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html).) – gidds Aug 07 '19 at 19:59
  • @gidds: This answer is very old too! But for a time-zone-aware type, I'd suggest `ZonedDateTime` rather than `LocalDateTime` or `Instant` - neither of those know about time zones. – Jon Skeet Aug 08 '19 at 06:58
  • @JonSkeet: I forgot I'd followed a link here :-)  And yes, I'm sure you're right about `ZonedDateTime`.  (I haven't used the new date & time API enough yet.) – gidds Aug 08 '19 at 08:23