Javascript date objects always one day behind [duplicate] - javascript

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.

Related

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));

How do I convert certain Date object to the corresponding time in germany? [duplicate]

This question already has answers here:
Convert date to another timezone in JavaScript
(34 answers)
Closed 2 years ago.
Let's say I have a Date object like this:
let dateToConvert = new Date(date_string) // represents certain time like 12th Aug 11PM in India
What I want to achieve is to design a function like this:
getGermanDate(dateToConvert): Date {
// What should be written here?
}
The function should return Date object that is the time in Germany at the time that is in dateToConvert object.
Thanks in advance.
Formatting of javascript dates is covered in numerous other questions. A particular timezone can be specified using the timeZone option with toLocaleString or for more control use the Intl.DateTimeFormat constructor and format option (timezones are specified using an IANA representative location to apply historic and DST changes), e.g.
let d = new Date();
// toLocaleString, default format for language de
console.log(d.toLocaleString('de',{timeZone:'Europe/Berlin', timeZoneName: 'long'}));
// DateTimeFormat.format with specific options
let f = new Intl.DateTimeFormat('de', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
hour12: false,
minute: '2-digit',
timeZone: 'Europe/Berlin',
timeZoneName: 'short'
});
console.log(f.format(d));
You might also be interested in this answer.
You could use native JavaScript functions to convert (toLocaleString), or you could use moment timezone (which is more flexible).
For the toLocaleString call I'm also specifying a Germany date format (by passing "de-DE" to the locale parameter, you could use whichever locale you wish.
function getGermanDate(input) {
return moment.tz(input, "Europe/Berlin");
}
/* Using moment timezone */
let timestamp = "2020-08-12 23:00:00";
let timeIndia = moment.tz(timestamp, "Asia/Kolkata");
let timeGermany = getGermanDate(timeIndia);
console.log("Time (India):", timeIndia.format("YYYY-MM-DD HH:mm"));
console.log("Time (Germany):", timeGermany .format("YYYY-MM-DD HH:mm"));
/* Using native JavaScript */
let dateToConvert = new Date("2020-08-12T23:00:00+0530");
console.log("Time (India, native):", dateToConvert.toLocaleString('en-IN', { timeZone: 'Asia/Kolkata' }));
console.log("Time (Germany, native):", dateToConvert.toLocaleString('de-DE', { timeZone: 'Europe/Berlin' }));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.25/moment-timezone-with-data-10-year-range.js"></script>

how to convert date object to formatted local date time string? [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 5 years ago.
I am trying to convert the date object to local time that is formatted by 'YYYYMMDDHHmmss'.
What I wanna do is like following.
var currentDate = new Date();
var timezone = "Asia/Tokyo";
var currentDateJst = moment(currentDate).tz(timezone).format('YYYYMMDDHHmmss');
I would like to know how to convert without moment-timezone library.
If you don't wanna use a library then there's no quick / easy way about. One way is just to add the difference from UTC.
For example tokoy is UTC+9. So now you can do:
const yourTime = new Date();
console.log('your date is: ' + yourTime);
const minutesFromUTC = yourTime.getTimezoneOffset();
const utcTime = new Date(yourTime.setMinutes(yourTime.getMinutes()+minutesFromUTC));
console.log('utc date is: ' + utcTime);
const tokyoFromUTC = 9*60; // Tokya is 9 hours
const tokyoTime = new Date(utcTime.setMinutes(utcTime.getMinutes()+tokyoFromUTC));
console.log('tokyo date is: ' + tokyoTime);
https://jsfiddle.net/fz79mdg2/
You can use the ECMAScript Internationalization API if you want to format according to date-time format of a specific timezone. For example:
new Intl.DateTimeFormat(
'ja-JP',
{
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
year: 'numeric', // 2018
month: '2-digit',
day: '2-digit',
timezone: 'Asia/Tokyo' // Format in the order how it's used in Asia/Tokyo
}
).format(new Date()).replace(/\D/g, '')
At the end, I just removed the non-numeric chars to display in the way you asked.
There is good documentation in MDN regarding Intl.DateTimeFormat

Utilities.formatDate and timezone not working?

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.

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