简体   繁体   中英

Local system date format

I have a readonly field in HTML form. Here, I need to display the date (which comes from backend system) in the format which is relevant for the locale system of the user. This being an editable field, User may enter the date as per the system setting.

I was wondering how can I can get the system date format (ie it can be dd.MM.yyyy, MM/dd/YYYY, dd-MM-YYYY, YYYY-MM-dd based on the system settings in user's PC) using Javascript or jQuery.

Regards,

SAP Learner

You Can get system date using build in function in JS

 var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; var yyyy = today.getFullYear(); if(dd<10) { dd = '0'+dd } if(mm<10) { mm = '0'+mm } today = mm + '/' + dd + '/' + yyyy; document.write(today) document.write("<br>") // OR other solution document.write(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString().split('.')[0].replace('T',' ')); 

I will assume that the HTML field is a HTML5 date type field. Depending of the browser and language locale the front end user format could be seen differently, but the underlying value is always defined by the format yyyy-mm-dd . Also, when a form containing a date field is posted, the server side will receive also this format.

Dates on Javascript are based on the object Date . But this, additional of the Calendar date, also includes time, microseconds and timezone. To get the current user system date browser formatted on the user locale, can be done using.

var dateLocale= new Date().toLocaleString();

If the date input by the user, using a date input field, getting just the value will give the format 'yyyy-mm-dd'. However there is a way to retrieve the content using the method valueAsDate . This will return a Date object. However this Date object will have the time at 12:00 AM at GMT timezone. When you try to retrieve the locale date part, the content could be wrong because it's on the wrong timezone. To workaround the issue add the timezone offset minutes to the Date object to get you the correct locale time and date.

var dv=document.getElementById('date_field').valueAsDate;
dv.setMinutes(dv.getTimezoneOffset());
var datelocale=dv.toLocaleDateString;

Now you can do whatever you want with datelocale variable, but not try to put it back to a date input field as it could be incompatible. You could put it into a text input type or a hidden type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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