Utilities.formatDate and timezone not working? - javascript

I'm trying to output date with full words for day and month in French in a google spreadsheet script. (properties of spreadsheet and script has been set to (GMT+01:00) Paris)
var timezone = "Europe/Paris";
var date = new Date(2018,1,5,15,01,0,0);
var dateString = Utilities.formatDate(date, timezone, "EEEE d MMMM");
Logger.log(dateString);
Output is :
"Monday 5 February"
and when I try with a javascript function in the script :
dateString = date.toLocaleDateString("fr-FR", { weekday: "long", year: "numeric", month: "long", day: "numeric" });
Logger.log(dateString);
Output is :
"5 February 2018"
And when I check in Safari console with the same function,
var date = new Date(2018,1,5,15,01,0,0);
date.toLocaleDateString("fr-FR", { weekday: "long", year: "numeric", month: "long", day: "numeric" });
Output is :
"lundi 5 février 2018"
Code is good but it doesn't work for the script, I don't get it ...

If your app needs to support more locales than English, you'll need to get Node to load the extra locale data, or use intl npm package to patch the runtime with the Intl polyfill. Node.js versions prior to 0.12 and ≥v3.1 don't provide the Intl APIs, so they require that the runtime is polyfilled.

Related

How to format the date to (dd/mm/yyyy hh:mm:ss)

How can I convert the date below into this template (dd/mm/yyyy hh:mm:ss) ?
05/04/2021 14:52
I tried to do it that way, but I only get the time and not the date with time.
var data = new Date('05/04/2021 14:52');
var time = data.toLocaleTimeString('pt-PT', {hour12: false});
console.log(time);
You can use below script
var data = new Date('05/04/2021 14:52');
console.log(data.toLocaleString('en-GB',{hour12: false}));
Output : "04/05/2021, 14:52:00"
If you need more date-related staff than simple date formatting, you can use Moment.js.
moment().format('MMMM Do yyyy, h:mm:ss a'); // April 5th 2021, 9:16:13 pm
moment().format('DD/MM/yyyy hh:mm'); // 05/04/2021 21:18
If you need to format your date object, simply use:
moment(date).format('DD/MM/yyyy hh:mm');
Moment.js is also useful for operation on dates like days, week, month adding/subtracting, getting the start of a week, month, quarter, and many other useful operations.
This is my solution. If you want to create a advanced format, you can read more about object Intl
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl
const formatDate = new Intl.DateTimeFormat("en" , {
day: "2-digit",
month: "2-digit",
year: "numeric",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false
});
console.log(formatDate.format(new Date('05/04/2021 14:52')))

convert string date and time to utc based on timezone using moment

am using moment in nodejs server to convert local time from frontend to utc.
my time format is date = '10-07-2020 08:45 PM' in string format. When i use moment(date).format() its converting format to this 2020-10-07 20:45:00+05:30 timezone is adding based on server and i have timezone = '+4:00' this is my local timezone. I would like to convert my date string to UTC based on the timezone field not based on the server timezone. How can I do this?
I tried the following methods but am not getting a proper solution
moment.utc(moment(date).utcOffset(timezone)).format('YYYY-MM-DD HH:mm:ss')
Anyone Please suggest
You can use moment-timezone to create a date from a string and a certain timezone. In order to do that you need to specify your format and the corresponding timezone. Something like this:
const date = moment.tz("10-07-2020 08:45 pm", "M-D-YYYY hh:mm a", "Europe/Samara");
console.log(date.toISOString());
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.min.js"></script>
Instead of moment, perhaps use intl DateTimeFormat?
Here are some possibilities
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', };
const date = new Date('10-07-2020 08:45 PM')
console.log(date)
options.timeZone = 'Europe/Ulyanovsk';
options.timeZoneName = 'short';
console.log(new Intl.DateTimeFormat('en-US', options).format(date));

JavaScript full names for day-of-week and month (or How to get the date names per client locale)

The string that is returned from (new Date()).toString() looks something like this:
"Tue Nov 22 2016 14:14:51 GMT-0800 (Pacific Standard Time)"
Is there a built-in method/constructor that we can use that will not abbreviate the day-of-week and/or month? In other words, does JS support this:
"Tuesday November 22 2016 14:14:51 GMT-0800 (Pacific Standard Time)"
The reason for my question is because I'm looking for a lazy/hacky way that we might be able to get the Weekday and Month names in the language of the client.
If you don't need to support old browsers (older than IE 11), you can use toLocalDateString().
Example:
new Date().toLocaleDateString('en-US', {
weekday: 'long',
month: 'long',
day: 'numeric',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZoneName: 'short'
})
But moment.js is way more comfortable.
See MDN Date.prototype.toLocaleDateString() for more information.
As Josa's answer implies, it is possible to get the full names for the weekday and month (for most modern browsers).
I used the .toLocaleDateString() to extract the full names of the weekday and month in the language of the client successfully using Chrome and IE11 (it does NOT work in Safari 9).
Extending the idea of getting the full names from the browser, I was curious if we could, then, get the name of the weekday and the name of the month in the language that matches the client's locale. The following experiment shows that that it is possible (although, not reliable).
For Experiment/Fun:
The following function will return an object that includes the name of the Weekday and Month for a particular date in the language of a particular locale-code.
Fiddle
function getWeekdayAndMonthNamesByLocaleCode(localeCode, date) {
var Names = {
Weekday: "",
Month: ""
};
if (!(date instanceof Date && !isNaN(date.valueOf()))) {
date = new Date();
}
if (localeCode == null || localeCode.length < 2) {
localeCode = navigator.language;
}
Names.Month = date.toLocaleDateString(localeCode, {
month: 'long',
});
Names.Weekday = date.toLocaleDateString(localeCode, {
weekday: 'long'
});
return Names;
}
I haven't tested the function for browser compatibility and I certainly wouldn't rely on it to work for all languages, but I thought it was interesting enough to post here for others to experiment with.

Javascript date objects always one day behind [duplicate]

This question already has answers here:
Wrong Date in Javascript
(3 answers)
Closed 6 years ago.
I am trying to convert a date object from the backend db to a string to present on the view, however, when I convert it, the result is always one day behind.
The code:
date = this.props.date;
d = new Date(date)
options = {
month: "long", weekday: "long", year: "numeric",
day: "numeric"
};
dateStr = d.toLocaleDateString("en-us",options)
EDIT examples provided:
Regarding backend structure, the date is inserted into the database via a simple html datepicker form.
Currently, this.props.date, if rendered on the view, will render something like this:
"2016-10-01"
When I use the code above, it would become:
"Friday, September 30, 2016"
Assuming your backend date is in UTC specifically ISO8601 and you want the displayed date to be UTC in en-us language-region.
var date = "2016-10-01";
var parts = date.split('-');
parts[1] -= 1;
var d = new Date(Date.UTC.apply(null, parts));
options = {
month: "long",
weekday: "long",
year: "numeric",
day: "numeric",
timeZone: 'UTC'
};
document.getElementById('out').textContent = d.toLocaleDateString("en-us", options);
<pre id="out"></pre>
Assuming the date is UTC and the Date object handles ISO8601 correctly (some older versions do not) then you could rely on the built in parsing of Date.
var date = "2016-10-01";
var d = new Date(date);
options = {
month: "long",
weekday: "long",
year: "numeric",
day: "numeric",
timeZone: 'UTC'
};
document.getElementById('out').textContent = d.toLocaleDateString("en-us", options);
<pre id="out"></pre>
So all I have done is explicitly set the output to be UTC, otherwise it is using your runtime's default time zone. Worth noting that toLocaleDateString is still in its infancy and can vary across browsers, just like ISO8601 parsing.

Locale specific date without year

I am using https://github.com/abritinthebay/datejs/ for date formatting due to locale support. However, is it not possible to get a full date time without year?
Example
Input date:2014/09/20 20:00:00
Output date: 09/20 20:00
And it has to respect locale settings!
Looks like since ES2015 you can just skip first parameter and set only 'options' parameter, in that way locale will be applied:
new Date().toLocaleString(undefined, {
month: "short", day: "numeric",
hour: "numeric", minute: "numeric", second: "numeric"
}) // "Jul 11, 5:50:09 PM"
I didn't find the way to remove comma between date and time. For that case string formatting can be used:
const dateTime = new Date();
const datePart = dateTime.toLocaleDateString(undefined, {month: "short", day: "numeric"});
const timePart = dateTime.toLocaleTimeString();
const result = `${datePart} ${timePart}`;
// "Jul 11 5:57:10 PM"
console.log(new Date().toLocaleString('en-En',{weekday: "long", month: "long", day: "numeric"}))
You can change this options as you want.
To format a date as month/day hour:minute with Date.js you'd call toString with the format 'MM/DD HH:mm' to get two digits for all values, e.g.:
console.log(new Date().toString('MM/dd HH:mm'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js"></script>
Attempting to determine the format that the user expects to see is very problematic, whether it's referred to as "culture", "locale" or just "preference". Javascript doesn't have access to system settings and the browser doesn't reveal them. You can try to guess based on the output of Date.prototype.toLocaleString, but that is entirely implementation dependent and doesn't necessarily conform to user preferences.
One common approach is to use an unambiguous format so user preferences don't matter, e.g.
console.log(new Date().toString('dd-MMM HH:mm'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js"></script>
Another approach is to have an unambiguous default format, then allow the user to select from a few supported formats and store the preference.
There is also the built–in Date.prototype.toLocaleString, which is pretty unreliable but some browsers support the optional ECMA-402 Intl formatting options. It's pretty ordinary as a formatter so really can't be recommended when there are libraries that do the job so much better, e.g.
var options = {
month: 'short',
day : '2-digit',
hour : '2-digit',
minute:'2-digit'
};
// Browser dependent, something like en-us: Jan 21, 8:39 AM
console.log('en-us: ' + new Date().toLocaleString('en-us',options))
// Browser dependent, something like en-gb: 21 Jan, 08:39
console.log('en-gb: ' + new Date().toLocaleString('en-gb',options))
Yet another approach is to write your own parser and formatter that does just what you need. If you only need to support one or two formats, it's pretty straight forward, e.g.
// input format yyyy/mm/dd hh:mm:ss
function parseDateString(ds) {
var d = ds.split(/\D+/);
return new Date(d[0], --d[1], d[2], d[3], d[4], d[5]);
}
// Return date string as mm/dd hh:mm
function formatDate(d) {
function z(n) {
return (n < 10 ? '0' : '') + n
}
return z(d.getMonth() + 1) + '/' + z(d.getDate()) +
' ' + z(d.getHours()) + ':' + z(d.getMinutes());
}
console.log(formatDate(parseDateString('2014/09/20 20:00:00'))); // 09/20 20:00
So you can replace an entire library with less than a dozen lines of code. :-)

Categories

Resources