Java date format to JavaScript date format
Asked Answered
D

11

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.

Dispersive answered 17/6, 2009 at 15:21 Comment(5)
"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.Hindemith
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.Cairo
Did you mean "dd/mm/yy (07/06/09)"? Otherwise I don't understand the difference between the two sample dates you gave.Cyperaceous
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)?’Kelliekellina
(However I am still down-voting this question because if you need to do this, you’re doing it wrong).Kelliekellina
E
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().

Earpiercing answered 17/6, 2009 at 15:38 Comment(3)
I have a similar problem with Java Date -> Javascript Date -> DatePicker. This helped get me a lot closer. Thanks!Foreshow
Best solution. Solved the fact that SimpleDateFormat doesn't provide a zero based month.Philippi
Cleanest solution since it only depends on a universally available datum, making the JS-end easily reusable for non-Java clients as wellFlowerlike
S
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");
Sebastian answered 2/10, 2010 at 16:0 Comment(2)
What if my date is in this format // Jul 4, 2015 10:45:22 AM rather than // 2009-12-18 10:54:50.546Snout
Hi @Milson, jquery-dataFormat also supports it. Some examples: github.com/phstc/jquery-dateFormat/blob/master/test/…Sebastian
G
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.

Galegalea answered 17/6, 2009 at 15:33 Comment(1)
I really think a libary is the way to go on this one as well. FWIW, dojo has a good one as well. docs.dojocampus.org/dojo/date/localeUranian
K
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.

Kuchen answered 11/4, 2012 at 19:28 Comment(0)
R
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);
Rabah answered 28/11, 2010 at 6:19 Comment(0)
H
1

This works fine for me:

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

<script>
var d = new Date(<%=date.getTime()%>);
alert(d);
</script>
Herdic answered 7/10, 2011 at 12:55 Comment(0)
V
1

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

Vries answered 20/6, 2017 at 10:13 Comment(0)
K
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());
   
Keegan answered 31/12, 2022 at 9:17 Comment(0)
O
0

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

Oatcake answered 17/6, 2009 at 15:26 Comment(0)
T
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.

Thirteen answered 17/6, 2009 at 15:33 Comment(0)
P
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.

Portraiture answered 14/8, 2009 at 14:49 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.