简体   繁体   English

Java日期格式转JavaScript日期格式

[英]Java date format to JavaScript date format

I would like to be able to convert a Java date format string, eg dd/MM/yyyy (07/06/2009) to a JavaScript date format string, eg dd/mm/yy (07/06/2009).我希望能够将 Java 日期格式字符串(例如dd/MM/yyyy (07/06/2009))转换为 JavaScript 日期格式字符串,例如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. JavaScript 没有内置的日期格式化功能。 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.我正在使用 jQuery UI datepicker 并且我一直在设置它的日期格式,假设它会在某个时候调用标准的 JS function,而不是使用它自己的库,当我用谷歌搜索格式化字符串时,我直接跳到了什么字母的表格可用于。 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.无论如何,我必须提前 go 并且可能会写我自己的我猜,将 Java 日期格式字符串转换为 jQuery 日期格式字符串(或尽可能接近) - 我正在研究我们产品的 i18n 并创建了一个 java class 存储在整个应用程序中使用的首选日期格式字符串,我的意图是还能够为任何 jsps 提供与 JS 中等效的格式字符串。

Thanks anyway.不管怎么说,还是要谢谢你。

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() .如果您只需要将日期从 Java 传递到 JavaScript,我认为最好的方法是使用date.getTime()将 Java 日期转换为毫秒,创建一个 JavaScript 日期并使用new Date(milliseconds)的毫秒值初始化new Date(milliseconds)然后用 JavaScript Date object 的方式格式化日期,比如: date.toLocaleString()

You could use my plugin jquery-dateFormat .您可以使用我的插件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");

A similar topic has been answered here: Converting dates in JavaScript此处已回答类似主题: 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.如前所述,jQuery datepicker 有一个可行的解决方案,如果您可以负担得起应用程序的下载开销或已经在使用它。

Check out moment.js , It's "A lightweight javascript date library for parsing, manipulating. and formatting dates".查看moment.js ,它是“用于解析、操作和格式化日期的轻量级 javascript 日期库”。 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 .另外,值得一提的是 checkout date.js I think the two libraries complement each other.我认为这两个库是相辅相成的。

This JavaScript library should be able to help you.这个JavaScript库应该能帮到你。

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

(I don't know why they have it as a jQuery Plugin, because it works standalone.) (我不知道为什么他们把它作为 jQuery 插件,因为它是独立工作的。)

You'd simply split the original formatted date into its individual elements and then create a new Date Object with those elements.您只需将原始格式化日期拆分为其各个元素,然后使用这些元素创建一个新的日期 Object。 Then, use this library's "Date.f()" method to output it into any format you could want.然后,使用该库的“Date.f()”方法将 output 转换为您想要的任何格式。

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);

I suggest you the MomentJS with this Plugin that allow you to convert a Java pattern to a JS pattern (MomentJS)我建议您使用带有此插件MomentJS ,它允许您将 Java 模式转换为 JS 模式 (MomentJS)

On Java Side Java 侧

I recommend passing an Instant string which conforms to ISO 8601 standard.我建议传递符合ISO 8601标准的Instant字符串。

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 :样本运行中的 Output

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

ONLINE DEMO在线演示

Learn more about the modern Date-Time API from Trail: Date Time .Trail:Date Time中了解有关现代日期时间 API 的更多信息。

On JavaScript Side JavaScript 侧

Now, you can parse the ISO 8601 string on the JavaScript side simply by passing it as a parameter to Date constructor.现在,您只需将 JavaScript 端的 ISO 8601 字符串作为参数传递给Date构造函数即可进行解析。 You can also instantiate the Date object with the number of milliseconds from the epoch.您还可以使用纪元的毫秒数实例化Date object。

 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());

This works fine for me:这对我来说很好:

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

<script>
var d = new Date(<%=date.getTime()%>);
alert(d);
</script>

If you are using java, take a look at the Simple Date Format class.如果您使用的是 java,请查看简单日期格式class。

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".此页面中的 javascript 代码实现了一些日期函数,它们“使用与 java.text.SimpleDateFormat class 相同的格式字符串,但有一些小的例外”。 It is not the very same as you want but it can be a good start point.它与您想要的不太一样,但它可以是一个很好的起点。

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 DP_DateExtensions 库

Not sure if it'll help, but I've found it invaluable in several projects.不确定它是否有帮助,但我发现它在几个项目中非常宝贵。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM