简体   繁体   English

如何使用angular 2或javascript从客户端计算机获取日期和时间格式?

[英]How to get the Date & Time format From Client Machine using angular 2 or javascript?

transform(value: any): any {
    var customdate = new DatePipe(navigator.language);
    value = customdate.transform(value,"dd-mm-yyyy");
    return value;
}   

I need to get the date format of client's machine at the place of "dd-mm-yyyy". 我需要在“ dd-mm-yyyy”处获取客户端计算机的日期格式。

Unfortunately, there does not seem to be a way to get the preferred format for dates from the browser. 不幸的是,似乎没有办法从浏览器中获取日期的首选格式。 You can get certain information about the locale a user is in, and from that you might be able to divine the appropriate default values. 您可以获取有关用户所在区域的某些信息,并由此可以确定适当的默认值。 As an example, the following snippet uses the ECMAScript Internationalization API (which was released after how to get local date/time format? was answered): 例如,以下代码片段使用ECMAScript国际化API(回答了如何获取本地日期/时间格式后发布):

 console.log(new Intl.DateTimeFormat().resolvedOptions()) /* On my machine, this outputs: { "locale": "en-US", "calendar": "gregory", "numberingSystem": "latn", "timeZone": "America/New_York", "year": "numeric", "month": "numeric", "day": "numeric" } */ 

From that information, you should be able to use a server-side language/framework to construct the necessary format. 根据这些信息,您应该能够使用服务器端语言/框架来构造必要的格式。 For instance, in .NET, using C#: 例如,在.NET中,使用C#:

var culture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
var dateTimeInfo = culture.DateTimeFormat;
var formats = dateTimeInfo.GetAllDateTimePatterns();
// formats now contains a list of formats for this culture

Just get the current date with the Javascript Date object. 只需使用Javascript Date对象获取当前日期。

var currentDate = new Date();

https://www.w3schools.com/js/js_dates.asp https://www.w3schools.com/js/js_dates.asp

and use then the toLocaleDateString() function to get in the locale format. 然后使用toLocaleDateString()函数获取语言环境格式。

console.log(date.toLocaleDateString());

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

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

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