JavaScript - Get system short date format - javascript

Is there any way to get system short date format in JavaScript?
For example whether system's short date is in American format eg. m/d/Y or in european eg. d/m/Y
Please note:
This is not question about formatting date or calculating it based on geolocation, but about getting the format from the OS/system

After a pinch of research I concluded that technically it's not possible to get regional settings -and by this, date format- but you can do several other things. Pick one of these options:a) The already mentioned -and outdated- "toLocaleString()" function:
var myDate = new Date(1950, 01, 21, 22, 23, 24, 225);
var myDateFormat = myDate.toLocaleString();
alert (myDateFormat);
ISSUES:1) You can't "myDateFormat.replace" to get the date mask as month is not stored as "01", "02", etc in the string but as text instead, based on locale (like "February" in English but it's "Φεβρουάριος" in Greek and who knows what in e.g. Klingon).2) Different behavior on different browsers3) Different behavior on different OS and browser versions...b) Use the toISOString() function instead of toLocaleString(). You won't get the locale date mask but get a date from which you can tell where's which part of the date (ie where "month" or "day" is in that string). You can also work with getUTCDate(), getUTCMonth() and getUTCDay() functions. You still can't tell what date format the client uses, but can tell which Year/Month/Day/etc you work with when you grab a date; use the code above to test the functions I mentioned here to see what you can expect.c) Read
Inconsistent behavior of toLocaleString() in different browser article and use the (IMHO great) solution described there

for my case i used a custom date that i know what number is day, what is month and what is year so it can possible with a simple replace statement.
let customDate = new Date(2222, 11, 18);
let strDate = customDate.toLocaleDateString();
let format = strDate
.replace("12", "MM")
.replace("18", "DD")
.replace("2222", "yyyy");

It is not possible. You can get culture from user browser and use some js libraries to convert to correct date format. http://code.google.com/p/datejs/

I made a function to determine the client date format. The function determine
the date format separator, and also determine the 1st, 2nd and third part of
the date format.
getDateFormat(){
// initialize date value "31st January 2019"
var my_date = new Date(2019,0,31);
console.log(my_date.toLocaleDateString());
// Initialize variables
var separator="";
var first="";
var second="";
var third="";
var date_parts = [];
// get separator : "-", "/" or " ", format based on toLocaleDateString function
if (my_date.toLocaleDateString().split("-").length==3){
separator = " - ";
date_parts = my_date.toLocaleDateString().split("-");
}
if (my_date.toLocaleDateString().split("/").length == 3) {
separator = " / ";
date_parts = my_date.toLocaleDateString().split("/");
}
if (my_date.toLocaleDateString().split(" ").length == 3) {
separator = " ";
date_parts = my_date.toLocaleDateString().split(" ");
}
// get first part
if (date_parts[0]==2019){
first ="yyyy";
} else if (date_parts[0] == 31){
first = "dd";
} else{
if (date_parts[0].length<=2){
first ="mm";
}
else{
first="mmm";
}
}
// get second part
if (date_parts[1] == 2019) {
second = "yyyy";
} else if (date_parts[1] == 31) {
second = "dd";
} else {
if (date_parts[1].length <= 2) {
second = "mm";
}
else {
second = "mmm";
}
}
// get third part
if (date_parts[2] == 2019) {
third = "yyyy";
} else if (date_parts[2] == 31) {
third = "dd";
} else {
if (date_parts[2].length <= 2) {
third = "mm";
}
else {
third = "mmm";
}
}
// assembly
var format = first + separator + second + separator + third;
console.log(format);
return format;
}

I've created a workaround to determine which format the user's browser is using.
This is in C# but the logic is the same:
Here are the steps:
First try to convert the user's browser date into American format (mm-dd-yyyy). Convert.ToDateTime is using the American date format.
If that fails it means the user is using European format (dd-mm-yyyy).
However, this will only cover the day 13 to 31 because this is not a valid month.
If the conversion is successful, do another check to determine if the converted date is between the current UTC day + 1 day (to cover UTC+14) and current UTC day - 1 day (to cover UTC-12).
https://www.timeanddate.com/time/current-number-time-zones.html
If the converted date is out of the current date range, it means the user's browser is using European format (dd-mm-yyyy) and you can convert it to American format if you want.
string localeDateString = "01/11/2020"; // e.g. input is using European format (dd-mm-yyyy)
var localeDate = new DateTime();
try
{
localeDate = Convert.ToDateTime(localeDateString);
//var checkTheFormatOfDateInput = localeDate.ToLongDateString();
var currentDateTime = DateTime.UtcNow;
//var currentDateTime = Convert.ToDateTime("11/01/2020");
//var checkTheFormatOfCurrentDate = Convert.ToDateTime("11/01/2020").ToLongDateString();
var currentDateTimePositive = currentDateTime.AddDays(1);
var currentDateTimeNegative = currentDateTime.AddDays(-1);
var outOfCurrentDateRange = !(localeDate.Ticks > currentDateTimeNegative.Ticks && localeDate.Ticks < currentDateTimePositive.Ticks);
if (outOfCurrentDateRange)
{
localeDate = DateTime.ParseExact(localeDateString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
}
catch
{
localeDate = DateTime.ParseExact(localeDateString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
//var checkTheEndResultFormat = localeDate.ToLongDateString();
Below is the clean code wrapped in a method:
private DateTime ConvertAmericanOrEuropeanDateFormatToAmericanDateFormat(string localeDateString)
{
var localeDate = new DateTime();
try
{
localeDate = Convert.ToDateTime(localeDateString);
var currentDateTime = DateTime.UtcNow;
var currentDateTimePositive = currentDateTime.AddDays(1);
var currentDateTimeNegative = currentDateTime.AddDays(-1);
var outOfCurrentDateRange = !(localeDate.Ticks > currentDateTimeNegative.Ticks && localeDate.Ticks < currentDateTimePositive.Ticks);
if (outOfCurrentDateRange)
{
localeDate = DateTime.ParseExact(localeDateString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
}
catch
{
localeDate = DateTime.ParseExact(localeDateString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
return localeDate;
}

A very good but lengthy answer can here found here: https://stackoverflow.com/a/9893752/2484903
A shorter one here:
let customDate = new Date(2222, 3, 8);
let strDate = customDate.toLocaleDateString();
let format = strDate
.replace("04", "MM")
.replace("4", "M")
.replace("08", "dd")
.replace("8", "d")
.replace("2222", "yyyy")
.replace("22", "yy");
console.log(format);
We create a date object of a known date and then parse the outcome.
First we look for "04" (which corresponds to 3 from the date definition); that would be the two digit month format MM. If not found, it must be the single digit format M. Afterwards do the same for day and year.

It should do the job...
function getSystemDateLocale(){
let testDate = (new Date('2000-1-30')).toLocaleDateString()
if (testDate.substring(0,2) == '30') return 'EU'
else return 'US'
}

Use Date.CultureInfo.formatPatterns.shortDate

Related

(getDate() - 1) function is getting the value zero if the current date is 1

My Requirement:
I'm having to fields Start Date and End Date, If the End Date is left empty while saving the record, the End Date Field value is populated with plus 1 year based on the entered from date.
My Issue:
If the Start Date is "9/1/2016" and the End Date is Left Empty means it should automatically populate the End Date value as "8/31/2016" but it returning the End Date value as "9/0/2016" and also i'm getting the following ERROR MESSAGE
Error: JS_EXCEPTION
INVALID_FLD_VALUE You have entered an Invalid Field Value Invalid Date for the following field: custrecord_end_date
CODE:
SCRIPT : CLIENT SCRIPT, EVENT :SaveRecord
function saveRecord(scriptContext) {
var newRecord= scriptContext.currentRecord;
var fromDate = new Date(newRecord.getValue('custrecord_created_date'));
var endDate = newRecord.getValue('custrecord_end_date');
if (endDate == null || endDate == '') {
//getting plus 1 year based on the From Date
tempEndDate = addingPlusYearOfTheCurrentDate(fromDate);
//setting the value to the End Date Field
newRecord.setValue('custrecord_end_date', tempEndDate);
}
}
// Add Plus Year from the Start Date when the End Date is Empty
function addingPlusYearOfTheCurrentDate(fromDate ) {
var date = new Date();
var Month = (fromDate.getMonth() + 1);
var Dates = (fromDate.getDate() - 1);
var Year = (fromDate.getFullYear() + 1);
var last_Day = new Date(Month + '/' + Dates + '/' + Year);
log.debug('last_Day:', last_Day);
return last_Day;
}
Not sure why you expected to be able to subtract 1 from 1 and get anything other than 0, but you can solve this problem by using the Date object's setFullYear() and setDate().
function addingPlusYearOfTheCurrentDate(fromDate) {
var date = new Date(fromDate);
date.setFullYear(date.getFullYear() + 1);
date.setDate(date.getDate() - 1);
return date;
}
console.log(addingPlusYearOfTheCurrentDate(new Date(2015, 10, 1)));
You should use the method nlapiStringToDate() for string to date conversions, as NetSuite gives date field value as string, which you must convert to date, and before you set back date, you must use nlapiSetFieldValue(YOUR_FIELD_ID, nlapiStringToDate(dateObject))
Please see below on suggested usage on reading and setting date fields.
function saveRecord(scriptContext) {
var newRecord = scriptContext.currentRecord;
var fromDate = nlapiStringToDate(newRecord.getValue('custrecord_created_date'));
var endDate = nlapiStringToDate(newRecord.getValue('custrecord_end_date'));
if (endDate == null || endDate == '') {
//getting plus 1 year based on the From Date
tempEndDate = addingPlusYearOfTheCurrentDate(fromDate);
//setting the value to the End Date Field
newRecord.setValue('custrecord_end_date', nlapDateToString(tempEndDate));
}
Parsing strings with the Date constructor (and Date.parse, they are equivalent for parsing) is strongly recommended against since parsing is almost entirely implementation dependent and inconsistent. Manually parse strings with a custom function or use a library.
Adding a year to a Date is fairly simple, but it seems you want the date that is one day prior to the same date next year. So add one year then subtract one day.
// Parse m/d/y format string to a Date and validate the result
function parseMDY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[0], b[1]);
return d && d.getMonth() == b[0]? d : new Date(NaN);
}
// Add 1 year to a Date
function addYear(d) {
if (Object.prototype.toString.call(d) != '[object Date]') return;
d.setFullYear(d.getFullYear() + 1);
d.setDate(d.getDate() -1);
return d;
}
var d = parseMDY('9/1/2016');
console.log(d.toLocaleString())
addYear(d);
console.log(d.toLocaleString())
Note that for 29 February, adding one year gives 1 May, then subtracting one day will give 28 February.
Is this a 1.0 or 2.0 script?
NetSuite's 1.0 API offers a couple date manipulation methods that might be helpful to you here: nlapiAddMonths and nlapiAddDays, as well as the Date-String conversion methods.
Here's an example of what you could do in 1.0
// 1.0 API does not pass scriptContext to saveRecord
function saveRecord() {
// Use nlapiStringToDate instead of raw Date constructor
var fromDate = nlapiStringToDate(nlapiGetFieldValue('custrecord_created_date'));
// Instead of the full extra conditional, just use || as fallback
var endDate = nlapiStringToDate(nlapiGetFieldValue('custrecord_end_date')) ||
calculateEndDate(fromDate);
// setting the value to the End Date Field
nlapiSetFieldValue('custrecord_end_date', nlapiDateToString(endDate));
}
/** #param fromDate {Date} */
function addYear(fromDate) {
return nlapiAddMonths(fromDate, 12);
}
/** #param fromDate {Date} */
function dayBefore(fromDate) {
return nlapiAddDays(fromDate, -1);
}
/** #param startDate {Date} */
function calculateEndDate(startDate) {
// add 1 year first, then subtract one day
return dayBefore(addYear(startDate));
}
If you're using 2.0 just add a comment, and I will try to update the example if I can. If you've got any questions about how this works, feel free to let me know as well.

Date Validation - how to work around Javascript's auto-correcting of dates?

I want to validate dates by Javascript and found this nice answer:
https://stackoverflow.com/a/1353711/3391783
but when i try to use it to validate dates, it seems like Javascript is auto-correcting my date by taking the closest valid date. so this will return true even though 2014-11-31 is not a valid date (Javascript months start at 0, so 10 equals November):
function isValidDate(d) {
if ( Object.prototype.toString.call(d) !== "[object Date]" )
return false;
return !isNaN(d.getTime());
}
var test_date = new Date(2014, 10, 31);
console.log( test_date );
console.log( isValidDate(test_date) );
seems like creating the Date is automatically switching it to 2014-12-01 which is a correct date.
but I would like to be able to validate user input without changing it.
So how can i create an invalid new Date() in Javascript?
Or is there a much simpler way to do this?
You can use the auto-correction in the Date object to validate the date. Just check the input against what you have in the Date object:
var y = 2014, m = 10, d = 31;
var test_date = new Date(y, m, d);
var valid =
test_date.getFullYear() == y &&
test_date.getMonth() == m &&
test_date.getDate() == d;
document.write(valid);
When it comes to handling dates in JavaScript, I'm a big fan of Moment.js. As you can see here, they do a good job of validating dates: http://momentjs.com/docs/#/parsing/is-valid/
new Date(2013, 25, 14).toString(); // "Sat Feb 14 2015 00:00:00 GMT-0500 (EST)"
moment([2015, 25, 35]).format(); // 'Invalid date'
Here's a function I wrote a while back that demonstrates Guffa's solution.
function isValidDate(checkDate) {
if(!/\d\d\/\d\d\/\d\d\d\d/.test(checkDate)) {
return false; // checkDate is not formatted as ##/##/####
} else {
// split checkDate into three pieces
var strMM = checkDate.split('/')[0];
var strDD = checkDate.split('/')[1];
var strYYYY = checkDate.split('/')[2];
// create new Date() object from split pieces
var strDateCheck = new Date(strYYYY,(strMM - 1),strDD);
// evaluate each piece of resulting date object against each corresponding piece of checkDate
if(((strDateCheck.getMonth() + 1) == strMM) && (strDateCheck.getDate() == strDD) && (strDateCheck.getFullYear() == strYYYY)) {
/* if you wish, add additional validation constraints here */
return true; // all three pieces match exactly
} else {
return false; // at least one piece did not match
}
}
}

Date formatting and comparing dates

I want to check to see if a date is before today. If it is then I want to display the date but not the time, if it is today then I want to display the time and not the date. The date I am checking is in the dd-mm-yyy hh:mm format and so they do not compare.
Please see what I have below so far:
var created = '25-05-2012 02:15';
var now = new Date();
if (created < now) {
created_format = [ format the date to be 25-05-2012 ]
} else {
created_format = [ format the date to be 02:15 ]
}
I have tried using now.dateFormat() and now.format() after seeing these in other examples but I get "is not a function" error messages.
Start by getting the parts of your date string:
var created = '25-05-2012 02:15';
var bits = created.split(/[-\s:]/);
var now = new Date();
// Test if it's today
if (bits[0] == now.getDate() &&
bits[1] == (now.getMonth() + 1) &&
bits[2] == now.getFullYear() ) {
// date is today, show time
} else {
// date isn't today, show date
}
Of course there are other ways, but I think the above is the easiest. e.g.
var otherDate = new Date(bits[2], bits[1] - 1, bits[0]);
now.setHours(0,0,0,0);
if (otherDate < now) {
// otherDate is before today
} else {
// otherDate is not before today
}
Similarly, once you've converted the string to a date you can use getFullYear, getMonth, getDate to compare with each other, but that's essentially the same as the first approach.
You can use getTime method and get timestamp. Then you can compare it with current date timestamp.

Validate two dates of this "dd-MMM-yyyy" format in javascript

I have two dates 18-Aug-2010 and 19-Aug-2010 of this format. How to find whether which date is greater?
You will need to create a custom parsing function to handle the format you want, and get date objects to compare, for example:
function customParse(str) {
var months = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'],
n = months.length, re = /(\d{2})-([a-z]{3})-(\d{4})/i, matches;
while(n--) { months[months[n]]=n; } // map month names to their index :)
matches = str.match(re); // extract date parts from string
return new Date(matches[3], months[matches[2]], matches[1]);
}
customParse("18-Aug-2010");
// "Wed Aug 18 2010 00:00:00"
customParse("19-Aug-2010") > customParse("18-Aug-2010");
// true
You can do the parsing manually, for your given format, but I'd suggest you use the date.js library to parse the dates to Date objects and then compare.
Check it out, its awesome!
And moreover, its a great addition to your js utility toolbox.
The native Date can parse "MMM+ dd yyyy", which gives:
function parseDMY(s){
return new Date(s.replace(/^(\d+)\W+(\w+)\W+/, '$2 $1 '));
}
+parseDMY('19-August-2010') == +new Date(2010, 7, 19) // true
parseDMY('18-Aug-2010') < parseDMY('19-Aug-2010') // true
Firstly, the 'dd-MMM-yyyy' format isn't an accepted input format of the Date constructor (it returns an "invalid date" object) so we need to parse this ourselves. Let's write a function to return a Date object from a string in this format.
function parseMyDate(s) {
var m = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'];
var match = s.match(/(\d+)-([^.]+)-(\d+)/);
var date = match[1];
var monthText = match[2];
var year = match[3];
var month = m.indexOf(monthText.toLowerCase());
return new Date(year, month, date);
}
Date objects implicitly typecast to a number (milliseconds since 1970; epoch time) so you can compare using normal comparison operators:
if (parseMyDate(date1) > parseMyDate(date2)) ...
Update: IE10, FX30 (and likely more) will understand "18 Aug 2010" without the dashes - Chrome handles either
so Date.parse("18-Aug-2010".replace("/-/g," ")) works in these browsers (and more)
Live Demo
Hence
function compareDates(str1,str2) {
var d1 = Date.parse(str1.replace("/-/g," ")),
d2 = Date.parse(str2.replace("/-/g," "));
return d1<d2;
}

Date Parsing and Validation in JavaScript

How would I achieve the pseudo-code below in JavaScript? I want to include the date check in the second code excerpt, where txtDate is for the BilledDate.
If ABS(billeddate – getdate) > 31 then yesno “The date you have entered is more than a month from today, Are you sure the date is correct,”.
if (txtDate && txtDate.value == "")
{
txtDate.focus();
alert("Please enter a date in the 'Date' field.")
return false;
}
Generally speaking you work with Date-objects in javascript, and these should be constructed with the following syntax:
var myDate = new Date(yearno, monthno-1, dayno);
//you could put hour, minute, second and milliseconds in this too
Beware, the month-part is an index, so january is 0, february is 1 and december is 11 !-)
Then you can pull out anything you want, the .getTime() thing returns number of milliseconds since start of Unix-age, 1/1 1970 00:00, så this value you could subtract and then look if that value is greater than what you want:
//today (right now !-) can be constructed by an empty constructor
var today = new Date();
var olddate = new Date(2008,9,2);
var diff = today.getTime() - olddate.getTime();
var diffInDays = diff/(1000*60*60*24);//24 hours of 60 minutes of 60 second of 1000 milliseconds
alert(diffInDays);
This will return a decimal number, so probably you'll want to look at the integer-value:
alert(Math.floor(diffInDays));
To get the date difference in days in plain JavaScript, you can do it like this:
var billeddate = Date.parse("2008/10/27");
var getdate = Date.parse("2008/09/25");
var differenceInDays = (billeddate - getdate)/(1000*60*60*24)
However if you want to get more control in your date manipulation I suggest you to use a date library, I like DateJS, it's really good to parse and manipulate dates in many formats, and it's really syntactic sugar:
// What date is next thrusday?
Date.today().next().thursday();
//or
Date.parse('next thursday');
// Add 3 days to Today
Date.today().add(3).days();
// Is today Friday?
Date.today().is().friday();
// Number fun
(3).days().ago();
You can use this to check for valid date
function IsDate(testValue) {
var returnValue = false;
var testDate;
try {
testDate = new Date(testValue);
if (!isNaN(testDate)) {
returnValue = true;
}
else {
returnValue = false;
}
}
catch (e) {
returnValue = false;
}
return returnValue;
}
And this is how you can manipulate JS dates. You basically create a date object of now (getDate), add 31 days and compare it to the date entered
function IsMoreThan31Days(dateToTest) {
if(IsDate(futureDate)) {
var futureDateObj = new Date();
var enteredDateObj = new Date(dateToTest);
futureDateObj.setDate(futureDateObj.getDate() + 31); //sets to 31 days from now.
//adds hours and minutes to dateToTest so that the test for 31 days is more accurate.
enteredDateObj.setHours(futureDateObj.getHours());
enteredDateObj.setMinutes(futureDateObj.getMinutes() + 1);
if(enteredDateObj >= futureDateObj) {
return true;
}
else {
return false;
}
}
}
Hello and good day for everyone
You can try Refular Expressions to parse and validate a date format
here is an URL yoy can watch some samples and how to use
http://www.javascriptkit.com/jsref/regexp.shtml
A very very simple pattern would be: \d{2}/\d{2}/\d{4}
for MM/dd/yyyy or dd/MM/yyyy
With no more....
bye bye

Categories

Resources