44

I would like to be able to convert a Java date format string, e.g. dd/MM/yyyy (07/06/2009) to a JavaScript date format string, e.g. dd/mm/yy (07/06/2009).

Has anyone done this before, or got any idea where I might find some code that already does this?

Edit:

Thanks for all the replies but now I realize my mistake and possibly why so many of you were struggling to understand the question; JavaScript doesn't have a built in date formatting ability. I am using the jQuery UI datepicker and I have been setting its date format, assuming it would be calling a standard JS function at some point, not using its own library! When I googled for formatting strings I jumped straight to the tables of what letters could be used, skipping the bit at the beginning explaining how to use the script.

Anyway I'll have to go ahead and possibly write my own I guess, converting a Java date format string into a jQuery date format string (or as close as possible) - I am working on the i18n of our product and have created a java class that stores the preferred date format string used throughout the application, my intention was to also have the ability to supply any jsps with the format string that is equivalent in JS.

Thanks anyway.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Ed .
  • 6,373
  • 8
  • 62
  • 82
  • 1
    "dd/mm/yy (07/06/2009)" does not compute, but I won't edit it because I'm not sure on exactly what you intend. – annakata Jun 17 '09 at 15:29
  • 1
    Could you give some information on how you are passing the Java date to the Javascript code? e.g. are you writing it out using a JSP? That will help a lot in answering your question. – Dónal Boyle Jun 17 '09 at 15:33
  • 1
    Did you mean "dd/mm/yy (07/06/09)"? Otherwise I don't understand the difference between the two sample dates you gave. – Nosredna Jun 17 '09 at 15:36
  • 2
    After reading this question about twenty times, I think Ed means ‘How do I convert a string used to format dates in Java (using SimpleDateFormat) to an equivalent string used to format dates in JavaScript (using Date.format)?’ – Daniel Cassidy Jun 17 '09 at 15:54
  • (However I am still down-voting this question because if you need to do this, you’re doing it wrong). – Daniel Cassidy Jun 17 '09 at 15:55

11 Answers11

50

If you just need to pass a date from Java to JavaScript, the best way to do it, I think, would be to convert the Java date to milliseconds using date.getTime(), create a JavaScript date initialized with this milliseconds value with new Date(milliseconds)and then format the date with the means of the JavaScript Date object, like: date.toLocaleString().

Ilya Boyandin
  • 3,069
  • 25
  • 23
  • 1
    I have a similar problem with Java Date -> Javascript Date -> DatePicker. This helped get me a lot closer. Thanks! – jjohn Feb 23 '12 at 14:50
  • 2
    Best solution. Solved the fact that SimpleDateFormat doesn't provide a zero based month. – cherouvim Jun 17 '14 at 08:56
  • 1
    Cleanest solution since it only depends on a universally available datum, making the JS-end easily reusable for non-Java clients as well – Angad Aug 02 '15 at 09:14
6

You could use my plugin jquery-dateFormat.

// Text
$.format.date("2009-12-18 10:54:50.546", "dd/MM/yyyy");
// HTML Object
$.format.date($("#spanDate").text(), "dd/MM/yyyy");
// Scriptlet
$.format.date("<%=java.util.Date().toString()%>", "dd/MM/yyyy");
// JSON
var obj = ajaxRequest();
$.format.date(obj.date, "dd/MM/yyyy");
Pablo Cantero
  • 6,239
  • 4
  • 33
  • 44
  • What if my date is in this format // Jul 4, 2015 10:45:22 AM rather than // 2009-12-18 10:54:50.546 – Milson Jul 04 '15 at 17:00
  • Hi @Milson, jquery-dataFormat also supports it. Some examples: https://github.com/phstc/jquery-dateFormat/blob/master/test/format_date_spec.js#L72 – Pablo Cantero Jul 05 '15 at 20:10
3

A similar topic has been answered here: Converting dates in JavaScript

I personally have found this to be a rather large pain and took the author's suggestion and used a library. As noted, jQuery datepicker has one that is a viable solution if you can afford the overhead of download for your application or already using it.

Community
  • 1
  • 1
jnt30
  • 1,367
  • 2
  • 15
  • 21
  • 1
    I really think a libary is the way to go on this one as well. FWIW, dojo has a good one as well. http://docs.dojocampus.org/dojo/date/locale – seth Jul 15 '09 at 18:08
2

Check out moment.js! It's "A lightweight javascript date library for parsing, manipulating, and formatting dates". It is a really powerful little library.

Here's an example...

var today = moment(new Date());
today.format("MMMM D, YYYY h:m A");        // outputs "April 11, 2012 2:32 PM"

// in one line...
moment().format("MMMM D, YYYY h:m A");     // outputs "April 11, 2012 2:32 PM"

Here's another example...

var a = moment([2012, 2, 12, 15, 25, 50, 125]);
a.format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Monday, March 12th 2012, 3:25:50 pm"
a.format("ddd, hA");                       // "Mon, 3PM"
a.format("D/M/YYYY");                      // "12/3/2012"

Also, its worth mentioning to checkout date.js. I think the two libraries complement each other.

Hristo
  • 45,559
  • 65
  • 163
  • 230
1

This JavaScript library should be able to help you.

http://plugins.jquery.com/project/fIsForFormat

(I don't know why they have it as a jQuery Plugin, because it works standalone.)

You'd simply split the original formatted date into its individual elements and then create a new Date Object with those elements. Then, use this library's "Date.f()" method to output it into any format you could want.

For example:

var dateOld = "11/27/2010",
    dateArr = date1.split("/"),
    dateObj = new Date(dateArr[2], dateArr[0], dateArr[1]),
    dateNew = dateObj.f("MMM d, yyyy");

document.write("Old Format: " + dateOld + "<br/>New Format: " + dateNew);
JaXoN
  • 19
  • 1
1

I suggest you the MomentJS with this Plugin that allow you to convert a Java pattern to a JS pattern (MomentJS)

André Vinícius
  • 411
  • 4
  • 12
1

On Java Side

I recommend passing an Instant string which conforms to ISO 8601 standard.

import java.time.Instant;

class Main {
    public static void main(String[] args) {
        Instant instant = Instant.now();

        // You can pass the following string to JavaScript
        String strInstant = instant.toString();
        System.out.println(strInstant);

        // If the number of milliseconds from epoch is required
        long millis = instant.toEpochMilli();
        System.out.println(millis);
    }
}

Output from a sample run:

2022-12-31T09:40:52.280726Z
1672479652280

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.

On JavaScript Side

Now, you can parse the ISO 8601 string on the JavaScript side simply by passing it as a parameter to Date constructor. You can also instantiate the Date object with the number of milliseconds from the epoch.

var date = new Date("2022-12-31T09:40:52.280726Z");
console.log(date.toISOString());

// Or if the number of milliseconds from epoch has been received
date = new Date(1672479652280);
console.log(date.toISOString());
   
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

This works fine for me:

<%
Date date = Calendar.getInstance().getTime();
%>

<script>
var d = new Date(<%=date.getTime()%>);
alert(d);
</script>
Naveed Kamran
  • 169
  • 2
  • 8
0

If you are using java, take a look at the Simple Date Format class.

Garreth Golding
  • 985
  • 2
  • 11
  • 19
Andrew
  • 1,853
  • 1
  • 14
  • 15
0

The javascript code in this page implements some date functions and they "use the same format strings as the java.text.SimpleDateFormat class, with a few minor exceptions". It is not the very same as you want but it can be a good start point.

Csaba_H
  • 8,215
  • 1
  • 41
  • 42
0

If you just want to format dates my date extensions will do that well - it also parses data formats and does a lot of date math/compares as well:

DP_DateExtensions Library

Not sure if it'll help, but I've found it invaluable in several projects.

Jim Davis
  • 1,230
  • 6
  • 11