Javascript String to date conversion without date format but passing locale - javascript

I have this user input date field, where user can enter date as string such '010117' or '01012017' which I am converting to US date standard format(MM/dd/yyyy) using JavaScript. If we have to go international we want user to input date as string as per their country standard.
Question is, Is there any library for JavaScript that we can use to pass the date as string and locale and it will convert the string to their locale standard date format.
We don't want to pass date format for each country as it will be too much of a task to do that for each country.
Thanks in advance.

There is JavaScript library MomentJS which provides very good features about date and time.
We can pass the string to MomentJS and it will give date.
By default MomentJS comes with English locale. You can change the locale by passing locale string to below function:
moment.locale(myLocale);
To get user's locale, you can do the following:
var myLocale = window.navigator.userLanguage || window.navigator.language;
Refer to the the link:
https://momentjs.com/docs/#/i18n/

Related

Parsing date from DD/MM/YYYY with Luxon javascript

I have a date in this format "DD/MM/YYYY" and I want to convert it to a DateTime object with Luxon library. How can I do it?
I know we can use methods like .fromISO(), .fromHTTP(), .fromSQL(), .fromJSDate(), and .fromFormat() and none of them accepts the format I have, for example: "31/12/2022"
I was trying with fromFormat( date, 'D' ) but it's invalid because "D" format is equal to "MM/DD/YYYY".
You can use fromFormat :
Create a DateTime from an input string and format string. Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see here.
passing "d/M/yyyy" as second argument. Example:
const DateTime = luxon.DateTime;
console.log(DateTime.fromFormat("31/12/2022", "d/M/yyyy").toISO());
<script src="https://cdn.jsdelivr.net/npm/luxon#3.1.1/build/global/luxon.min.js"></script>
Please have a look at Parsing section of the docs and Table of tokens to see the list of available tokens. As docs states:
Note that many tokens supported by the formatter are not supported by the parser.
in your case "D" is a format token you can use standalone tokens to parse your input string.

Working with date formats in Java and MySQL

Ok this is really bugging me.
I am developing a web app and I need to work with dates. When a date is displayed in a view, or whenever a date is entered into a form I need the format to be dd/mm/yyyy.
What data type do I choose for my SQL database columns which contain dates. 'Date' doesn't seem to work, do I use varchar?
But If I use varchar how do I use java script to perform arithmetic with dates.
Do I do some conversions server-side?
Please advise the best practices.
Also Im using laravel if theres any useful stuff already built in.
Date is the correct type to use in SQL DB.
To access the value use ISO date format "YYYY-MM-DD HH:mm:ss" .
You can create it from Java Date Object by using toISOString() method.
For easier time format conversion I can also recommend to check out Moment.js.
Best practice to save the date in MySQL table as date field only. Which saves the date string in YYYY-MM-DD HH:mm:ss format.
You need to make sure the following things.
Before inserting date into MySQL change the format of date string to YYYY-MM-DD HH:mm:ss.
When you retrieve the date from database convert the date string from YYYY-MM-DD HH:mm:ss to your desired format.
You can use SimpleDateFormat class in Java to convert the dates
format. Use format() function to format the date in desired and
parse() function to get the Java date object from string.
Reference: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
You should use varchar2 in mysql.
You can retrieve that varchar type date in javascript and create date object.
var d=dbdate;
var date = new Date(d);
And you can perform all javascript functions on date.
Hope it will help.
Javascript Date() object supports separate entries of date by:
var date=new Date();
var y=date.getFullYear();//4 digits
var m=date.getMonth()+1;//0-11 digits, plus 1 for true state
var d=date.getDate();//1-31
var dateSQL=y+'-'+m+'-'+d;//i.e 2016-07-25
you can use MySQL filed as datetime and also insert datetime format but when you will show then process it as you want as like
when you insert value in table then you can also format it as like
<?php $mysqltime = date ("Y-m-d H:i:s", $phptime); ?>
where $phptime is your input variable
$str = suppose $row['date'] (mysql filed value)
date("d/m/Y", strtotime($str));
where $str your retrieve date filed

JavaScript: Get date format from culture settings

I want to get Date format from my defined culture settings using JavaScript.
My Culture is defined in Web.config File as:
<globalization culture="en-GB" uiCulture="en-GB"/>
I am getting the defined Culture through
CultureInfo culture = System.Globalization.CultureInfo.CurrentUICulture;
and i am passing it to my client. And at Client side I am using momemt.js library to parse my json date in to actual date format.
var date = moment(JsonDate).toDate().toLocaleDateString(myCulture); //"en-GB"
and I am getting the date in the required date format as "16/07/2016"
but I also want to get this Format as dd/MM/yyyy so that I can use this culture date format in my html (for date picker).
Please let me know how can I get this date format using culture info at client side.
You can use AngularJS-s date filter
check this link please - https://docs.angularjs.org/api/ng/filter/date
You may install moment.js in your project. https://momentjs.com/
Include moment-with-locales.min.js in your HTML template.
In your JavaScript:
moment.locale(myCulture);
var date = moment(JsonDate).format('L')

How do I get this JavaScript / moment code to work with both US and UK date formats?

How do I get this JavaScript / moment code to work with both US (MM/DD/YYYY) and UK (DD/MM/YYYY) date formats? Currently it only works with a UK format:
moment.fn.toJSON = function() {
return this.format("YYYY-MM-DDTHH:mmZ");
};
function submitform() {
document.getElementById("st_dt_tm").value =
moment(document.getElementById("inp-st").value, "DD/MM/YYYY HH:mm").toJSON();
return true;
};
There is no way, by date format alone, to know if it is DD/MM/YYYY or MM/DD/YYYY because of dates like 01/02/2016, which is a valid (but different) date either way.
Your choices are:
Use MM/DD/YYYY for US dates and DD-MM-YYYY for European dates, which is similar to what the JavaScript Date object does, but even that is not entirely useful -- more details here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
The "best" option is to use some kind of cultural indicator flag -- either something passed in from the back-end code, or perhaps asking JavaScript to format a date for you and looking at what format they use -- and changing strings accordingly.

Manipulating dates in Javascript without the Date object

It appears I can't use the javascript Date object as it inherintly defaults to US dates when you initialise with a datestring. There is no way of passing any culture information to the date object
I.e. No matter what the clients locale settings are
var d = new Date("08/10/2009") will always create a date object representing the 10th August 2009 rather than the 8th October 2009 if the clients locale was the UK.
So given that my requirement is to be able to add/subtract days/months/years easily is there a clever way of doing this easily without the Date object
All i need to do is add a day to a date (or a string representation of a date). so if my code detects the locale setttings are in the US, when it sees a string like "10/08/2009" it whacks it up to "10/09/2009" but if it had detected it was in the UK it would have know it a uk string representation of a date and whacked it up to "09/10/2009"
For date manipulation and localization on JavaScript I always recommend the DateJS library.
This library abstracts the use of Date objects, has a very good localization options, powerful date parsing and formatting, and it also has a very nice fluent API.
If you know you are getting input formatted dd/mm/yyyy you can easily assemble the correct date.
function britDay(D){
D= D.match(/\d+/g);
return new Date(+D[2], D[1]-1, +D[0]);
}
toLocaleDateString will return the date in the format expected by the user.
Relying on the user input that obeys particular formatting rules is optimistic-
which is why most sites use separate, labeled inputs or select fields for the month, date and year.
You probably know that it's easy to add one day to a date, just add 86,400 * 1000 milliseconds to the date. It sounds like displaying in your locale is the issue; does Date.toLocaleString() not do the right thing for you?
dojo.date.locale.parse will be able to parse a formatted string according the locale of your choice. It has a table of cultural data based off unicode.org/cldr. See this article for more information.

Categories