How do I remove the Date part from JavaScript date? - javascript

I have a date 12/19/2016 8:54 in a variable. I want the value of only the time without the date. How do I do this?
Examples:
Input: 12/19/2016 8:54 Output: 8:54
Input: 2/2/2018 11:30 Output: 11:30
The only way I see this is string manipulation, which I believe is a bad idea.

you can use split method.
const time = '12/19/2016 8:54'.split(" ")[1];

If your date variable is an actual Date object then you can use Intl.DateTimeFormat to get it formatted any way you want. Here is how:
var d = new Date(2016, 11, 19, 8, 54);
console.log(d); // If you are not in UTC then this will show the Date with timezone adjustment applied
var hourAndMinute = { hour: "numeric", minute: "numeric" };
var formatter = new Intl.DateTimeFormat("en-GB", hourAndMinute);
var result = formatter.format(d); // This does the reverse timezone adjustment
console.log(result);

Related

Converting to UTC is giving NaN error in Javascript

I have below code which is giving NaN error when i am trying to convert it into Date.UTC format.
let sDate = "2019, 10, 19";
let min = Date.UTC(sDate);
whereas below code is giving me correct result
let min = Date.UTC(2019, 10, 19);
but as per my need, sDate is supposed to be passed as parameter because it may vary. How to correct this?
If you refer docs, Date.UTC does not take date string as an argument. It takes individual parts.
Date.UTC(year[, month[, day[, hour[, minute[, second[, millisecond]]]]]])
So when you pass Date.UTC('2019, 10, 19'), you are just passing year's value and not other values. Year's value is also not number. Hence NaN.
If you wish to create UTC date using date string, you will have to split values.
The date arguments are not a string:
let sDate = "2019, 10, 19";
let min = Date.UTC(...sDate.split(', '));
console.log(new Date(min));
You can use String.split (with destructuring) to convert a known date string format into year, month, day. You have do subtract 1 from the month value when passing to the Date.UTC function since this accepts a month value from 0 to 11 (January to December).
If you want to do more sophisticated Date parsing I strongly recommend you use a library such as Moment.js. This is well tested and has a very flexible API.
const sDate = "2019, 10, 19";
const [year, month, day] = sDate.split(",");
console.log("Date components:", {year, month, day});
// Date constructor takes a month from 0: January to 11: December
const utcDate = Date.UTC(year, month - 1, day);
console.log("Date (ISO):", new Date(utcDate).toISOString());
console.log("Date (toLocaleString):", new Date(utcDate).toLocaleString("en", { timeZone: "UTC"}));
The Date.UTC() method accepts parameters similar to the Date constructor but treats them as UTC
Date.UTC(year[, month[, day[, hour[, minute[, second[, millisecond]]]]]])
you can't use string directly
getData=(d)=>{
return [d.getFullYear(),d.getMonth(),d.getDate(), d.getHours(),d.getMinutes()];
};
let splited = getData(new Date('2019, 10, 19'))
console.log(new Date(Date.UTC(...splited)));

Is there a function to get the UTC date in the Locale String Format?

I want to get the current UTC date in JavaScript, but display it in the local date format (like Date.toLocaleDateString() does).
I first tried to just get the current UTC Date with Date.toUTCString() but that doesn't actually print out in the local format.
I then tried using the options configuration in toLocaleDateString(), but that just printed the local date and not the UTC date in the local format.
e.g. new Date().toLocaleDateString(options = {timeZone: "UTC"})
I then tried formatting using Intl.DateTimeFormat(), but that just gives the same results as Date.toLocaleDateString() does.
If there was a way to get the locale format then I'd be happy to use that format to format the UTC Date, but as far as I can tell there is none.
For example, given the new Date("Sat, 30 Mar 2019 00:27:19 GMT"), In the US, I should print out "3/30/2019", in Europe I should print out "30/3/2019", and so on, for every supported locale.
However, new Date("Sat, 30 Mar 2019 00:27:19 GMT").toLocaleDateString(options = {timeZone: "UTC"}) will print out "3/29/2019" instead.
I also wanted to display a date using localized string settings, like toLocaleDateString() does, but using the date's UTC value, instead of the local time zone.
For example:
I do want the localized string format, but I also want the UTC value instead of the local time zone value. The desired output in this example would be 4/3/2019, instead of 4/2/2019.
I acknowledged #AndersonHappens suggestion, but I have not used it. Here is what I did, instead:
There is a getTimezoneOffset() function, which provides the local time zone offset.
We can use this function result and create a new Date, applying the diff. Then, we can use toLocaleDateString() directly, as usual, to get the date in localized string format:
The solution as a function could be like this:
function toLocaleUTCDateString(date, locales, options) {
const timeDiff = date.getTimezoneOffset() * 60000;
const adjustedDate = new Date(date.valueOf() + timeDiff);
return adjustedDate.toLocaleDateString(locales, options);
}
Given a date, you can get the locale format with new Intl.DateTimeFormat().
You can then use formatToParts in order to get the formatting of the date and each specific component.
Following the example in the formatToParts documentation, I created the following method to get the UTC date in the locale string.
function toLocaleUTCDateString(date) {
let formatter = new Intl.DateTimeFormat();
return formatter.formatToParts(date).map(({type, value}) => {
switch (type) {
case 'day': return date.getUTCDate();
case 'hour': return date.getUTCHours();
case 'minute': return date.getUTCMinutes();
case 'month': return date.getUTCMonth() + 1;
case 'second': return date.getUTCSeconds();
case 'timeZoneName': return "UTC";
case 'year': return date.getUTCFullYear();
default : return value;
}
}).reduce((string, part) => string + part);
}
Do note however that this method does not remember number versus string formatting. For example, if you want to display the month of March as "March" (or the specific language month string), and not as the number 3, you would have to figure out how to do that yourself. It also doesn't handle discrepancies in weekdays, so if the local date is "Friday" and the UTC Date is "Saturday", you would have to figure that out separately as well.
You almost got it right - the timeZone option is available in the second argument. The first argument to toLocaleDateString is for the locales.
This example from your question works when options are the second argument (and is much simpler than other answers):
const usLocale = 'en-US'
new Date('Sat, 30 Mar 2019 00:27:19 GMT').toLocaleDateString(usLocale, {
timeZone: 'UTC',
})
// '3/30/2019'
const ukLocale = 'en-GB'
new Date('Sat, 30 Mar 2019 00:27:19 GMT').toLocaleDateString(ukLocale, {
timeZone: 'UTC',
})
// '30/03/2019'
var dateToPrint = new Date(Date.UTC(2020, 3, 23, 15, 0, 0));
new Date(
dateToPrint.getUTCFullYear(),
dateToPrint.getUTCMonth(),
dateToPrint.getUTCDate(),
dateToPrint.getUTCHours(),
dateToPrint.getUTCMinutes(),
dateToPrint.getUTCSeconds()
).toLocaleString('es-ES')
see image
Inside the toLocaleDateString you can pass options. There is an option name TimeZone. You have to set it to 'UTC'
const dateToParse = new Date()
dateToParse.toLocaleDateString(locate, { timeZone: 'UTC' })
Check out Intl.DateTimeFormat on MDN!
Using it is as simple as
// do this once in a central library file
const formatter = new Intl.DateTimeFormat('en', {
timeZone: 'UTC',
timeZoneName: 'short',
month: 'short',
day: '2-digit',
hour12: false,
hour: '2-digit',
minute: '2-digit',
})
// reuse anywhere for consistency
const myDate = new Date(
'Thu Feb 10 2022 12:50:14 GMT+0100'
)
formatter.format(myDate) === 'Feb 10, 11:50 UTC' // true
Open your console, copy-paste the code and start playing!
Again, Intl.DateTimeFormat on MDN.
Enjoy!
toLocaleString receives some parameters, the first parameter is the locale. To solve your issue specifically, you need to understand that UTC is not a locale. What you could to to accomplish what you want is to pass either 'en-US' for 3/29/2019 and 'en-GB' for 29/03/2019 hope that helps!

Format Date in Javascript

How to format this:
/Date(1292962456255)/
as regular looking date in JavaScript/jQuery?
This is what I call an "Microsoft Date" and the following function will convert the encoded date to a javascript date time
var msDateToJSDate = function(msDate) {
var dtE = /^\/Date\((-?[0-9]+)\)\/$/.exec(msDate);
if (dtE) {
var dt = new Date(parseInt(dtE[1], 10));
return dt;
}
return null;
}
Check out moment.js! It's "A lightweight javascript date library for parsing, manipulating, and formatting dates". It is a really powerful little library.
Here's an example...
var today = moment(new Date());
today.format("MMMM D, YYYY h:m A"); // outputs "April 11, 2012 2:32 PM"
// in one line...
moment().format("MMMM D, YYYY h:m A"); // outputs "April 11, 2012 2:32 PM"
Here's another example...
var a = moment([2012, 2, 12, 15, 25, 50, 125]);
a.format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Monday, March 12th 2012, 3:25:50 pm"
a.format("ddd, hA"); // "Mon, 3PM"
a.format("D/M/YYYY"); // "12/3/2012"
Also, its worth mentioning to checkout date.js. I think the two libraries complement each other.
The number is a timestamp with millisecond resolution. This number can be passed to JavaScript's Date class' constructor. All that is needed is some code to extract it from the string:
var dateString = "/Date(1292962456255)/";
var matches = dateString.match(/^\/Date\((\d+)\)\/$/);
var date = new Date(parseInt(matches[1], 10));
The regexp on the second line gets a bit messy since the string contains /, ( and ) at precisely the positions that they are needed in the regexp (are you sure what you have is strings that look like that, and not a description of a pattern that would extract them?).
Another way of doing it is to use eval:
var dateString = "/Date(1292962456255)/";
var date = eval("new " + dateString.substring(1, dateString.length - 1));
but that may open up for an XSS attack, so I don't recommend it.
I think this a microtime. Similar to PHP's microtime function. Or in new Date().getTime() in JavaScript.
// PHP
$ php -r "var_dump(microtime(true));"
float(1292963152.1249)
// JavaScript
new Date().getTime()
1292963411830

How to convert a full date to a short date in javascript?

I have a date like this Monday, January 9, 2010
I now want to convert it to
1/9/2010 mm/dd/yyyy
I tried to do this
var startDate = "Monday, January 9, 2010";
var convertedStartDate = new Date(startDate);
var month = convertedStartDate.getMonth() + 1
var day = convertedStartDate.getDay();
var year = convertedStartDate.getFullYear();
var shortStartDate = month + "/" + day + "/" + year;
However it must be thinking the date is in a different format since day returns 1 instead of 9.
Here you go:
(new Date()).toLocaleDateString('en-US');
That's it !!
you can use it on any date object
let's say.. you have an object called "currentDate"
var currentDate = new Date(); //use your date here
currentDate.toLocaleDateString('en-US'); // "en-US" gives date in US Format - mm/dd/yy
(or)
If you want it in local format then
currentDate.toLocaleDateString(); // gives date in local Format
The getDay() method returns a number to indicate the day in week (0=Sun, 1=Mon, ... 6=Sat). Use getDate() to return a number for the day in month:
var day = convertedStartDate.getDate();
If you like, you can try to add a custom format function to the prototype of the Date object:
Date.prototype.formatMMDDYYYY = function(){
return (this.getMonth() + 1) +
"/" + this.getDate() +
"/" + this.getFullYear();
}
After doing this, you can call formatMMDDYYY() on any instance of the Date object. Of course, this is just a very specific example, and if you really need it, you can write a generic formatting function that would do this based on a formatting string, kinda like java's SimpleDateeFormat (http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html)
(tangent: the Date object always confuses me... getYear() vs getFullYear(), getDate() vs getDay(), getDate() ranges from 1..31, but getMonth() from 0..11
It's a mess, and I always need to take a peek. http://www.w3schools.com/jsref/jsref_obj_date.asp)
Built-in toLocaleDateString() does the job, but it will remove the leading 0s for the day and month, so we will get something like "1/9/1970", which is not perfect in my opinion. To get a proper format MM/DD/YYYY we can use something like:
new Date(dateString).toLocaleDateString('en-US', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
})
Alternative: We can get similar behavior using Intl.DateTimeFormat which has decent browser support. Similar to toLocaleDateString(), we can pass an object with options:
const date = new Date('Dec 2, 2021') // Thu Dec 16 2021 15:49:39 GMT-0600
const options = {
day: '2-digit',
month: '2-digit',
year: 'numeric',
}
new Intl.DateTimeFormat('en-US', options).format(date) // '12/02/2021'
var d = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)");
document.getElementById("demo").innerHTML = d.toLocaleDateString();
date.toLocaleDateString('en-US') works great. Here's some more information on it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
I wanted the date to be shown in the type='time' field.
The normal conversion skips the zeros and the form field does not show the value and puts forth an error in the console saying the format needs to be yyyy-mm-dd.
Hence I added a small statement (check)?(true):(false) as follows:
makeShortDate=(date)=>{
yy=date.getFullYear()
mm=date.getMonth()
dd=date.getDate()
shortDate=`${yy}-${(mm<10)?0:''}${mm+1}-${(dd<10)?0:''}${dd}`;
return shortDate;
}
Although this question posted long long time ago, the proper way to do this is:
Intl.DateTimeFormat("en").format(new Date())
Any way, the Intl (international) object has many options you can pass to like to enforce tow digits etc.
You all can look at it here
I was able to do that with :
var dateTest = new Date("04/04/2013");
dateTest.toLocaleString().substring(0,dateTest.toLocaleString().indexOf(' '))
the 04/04/2013 is just for testing, replace with your Date Object.
You could do this pretty easily with my date-shortcode package:
const dateShortcode = require('date-shortcode')
var startDate = 'Monday, January 9, 2010'
dateShortcode.parse('{M/D/YYYY}', startDate)
//=> '1/9/2010'
Try this:
new Date().toLocaleFormat("%x");

Display date/time in user's locale format and time offset

I want the server to always serve dates in UTC in the HTML, and have JavaScript on the client site convert it to the user's local timezone.
Bonus if I can output in the user's locale date format.
Seems the most foolproof way to start with a UTC date is to create a new Date object and use the setUTC… methods to set it to the date/time you want.
Then the various toLocale…String methods will provide localized output.
Example:
// This would come from the server.
// Also, this whole block could probably be made into an mktime function.
// All very bare here for quick grasping.
d = new Date();
d.setUTCFullYear(2004);
d.setUTCMonth(1);
d.setUTCDate(29);
d.setUTCHours(2);
d.setUTCMinutes(45);
d.setUTCSeconds(26);
console.log(d); // -> Sat Feb 28 2004 23:45:26 GMT-0300 (BRT)
console.log(d.toLocaleString()); // -> Sat Feb 28 23:45:26 2004
console.log(d.toLocaleDateString()); // -> 02/28/2004
console.log(d.toLocaleTimeString()); // -> 23:45:26
Some references:
toLocaleString
toLocaleDateString
toLocaleTimeString
getTimezoneOffset
You can do it with moment.js (deprecated in 2021)
It's best to parse your date string from UTC as follows (create an ISO-8601 compatible string on the server to get consistent results across all browsers):
var m = moment("2013-02-08T09:30:26Z");
Now just use m in your application, moment.js defaults to the local timezone for display operations. There are many ways to format the date and time values or extract portions of it.
You can even format a moment object in the users locale like this:
m.format('LLL') // Returns "February 8 2013 8:30 AM" on en-us
To transform a moment.js object into a different timezone (i.e. neither the local one nor UTC), you'll need the moment.js timezone extension. That page has also some examples, it's pretty simple to use.
Note: Moment JS recommends more modern alternatives, so it is probably not a good choice for new projects.
You can use new Date().getTimezoneOffset()/60 for the timezone. There is also a toLocaleString() method for displaying a date using the user's locale.
Here's the whole list: Working with Dates
In JS there are no simple and cross platform ways to format local date time, outside of converting each property as mentioned above.
Here is a quick hack I use to get the local YYYY-MM-DD. Note that this is a hack, as the final date will not have the correct timezone anymore (so you have to ignore timezone). If I need anything else more, I use moment.js.
var d = new Date();
d = new Date(d.getTime() - d.getTimezoneOffset() * 60000)
var yyyymmdd = t.toISOString().slice(0, 10);
// 2017-05-09T08:24:26.581Z (but this is not UTC)
The d.getTimezoneOffset() returns the time zone offset in minutes, and the d.getTime() is in ms, hence the x 60,000.
2021 - you can use the browser native Intl.DateTimeFormat
const utcDate = new Date(Date.UTC(2020, 11, 20, 3, 23, 16, 738));
console.log(new Intl.DateTimeFormat().format(utcDate));
// expected output: "21/04/2021", my locale is Switzerland
Below is straight from the documentation:
const date = new Date(Date.UTC(2020, 11, 20, 3, 23, 16, 738));
// Results below assume UTC timezone - your results may vary
// Specify default date formatting for language (locale)
console.log(new Intl.DateTimeFormat('en-US').format(date));
// expected output: "12/20/2020"
// Specify default date formatting for language with a fallback language (in this case Indonesian)
console.log(new Intl.DateTimeFormat(['ban', 'id']).format(date));
// expected output: "20/12/2020"
// Specify date and time format using "style" options (i.e. full, long, medium, short)
console.log(new Intl.DateTimeFormat('en-GB', { dateStyle: 'full', timeStyle: 'long' }).format(date));
// Expected output "Sunday, 20 December 2020 at 14:23:16 GMT+11"
Once you have your date object constructed, here's a snippet for the conversion:
The function takes a UTC formatted Date object and format string.
You will need a Date.strftime prototype.
function UTCToLocalTimeString(d, format) {
if (timeOffsetInHours == null) {
timeOffsetInHours = (new Date().getTimezoneOffset()/60) * (-1);
}
d.setHours(d.getHours() + timeOffsetInHours);
return d.strftime(format);
}
// new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])
var serverDate = new Date(2018, 5, 30, 19, 13, 15); // just any date that comes from server
var serverDateStr = serverDate.toLocaleString("en-US", {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
})
var userDate = new Date(serverDateStr + " UTC");
var locale = window.navigator.userLanguage || window.navigator.language;
var clientDateStr = userDate.toLocaleString(locale, {
year: 'numeric',
month: 'numeric',
day: 'numeric'
});
var clientDateTimeStr = userDate.toLocaleString(locale, {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
});
console.log("Server UTC date: " + serverDateStr);
console.log("User's local date: " + clientDateStr);
console.log("User's local date&time: " + clientDateTimeStr);
Here's what I've used in past projects:
var myDate = new Date();
var tzo = (myDate.getTimezoneOffset()/60)*(-1);
//get server date value here, the parseInvariant is from MS Ajax, you would need to do something similar on your own
myDate = new Date.parseInvariant('<%=DataCurrentDate%>', 'yyyyMMdd hh:mm:ss');
myDate.setHours(myDate.getHours() + tzo);
//here you would have to get a handle to your span / div to set. again, I'm using MS Ajax's $get
var dateSpn = $get('dataDate');
dateSpn.innerHTML = myDate.localeFormat('F');
The .getTimezoneOffset() method reports the time-zone offset in minutes, counting "westwards" from the GMT/UTC timezone, resulting in an offset value that is negative to what one is commonly accustomed to. (Example, New York time would be reported to be +240 minutes or +4 hours)
To the get a normal time-zone offset in hours, you need to use:
var timeOffsetInHours = -(new Date()).getTimezoneOffset()/60
Important detail:
Note that daylight savings time is factored into the result - so what this method gives you is really the time offset - not the actual geographic time-zone offset.
With date from PHP code I used something like this..
function getLocalDate(php_date) {
var dt = new Date(php_date);
var minutes = dt.getTimezoneOffset();
dt = new Date(dt.getTime() + minutes*60000);
return dt;
}
We can call it like this
var localdateObj = getLocalDate('2015-09-25T02:57:46');
I mix the answers so far and add to it, because I had to read all of them and investigate additionally for a while to display a date time string from db in a user's local timezone format.
The datetime string comes from a python/django db in the format: 2016-12-05T15:12:24.215Z
Reliable detection of the browser language in JavaScript doesn't seem to work in all browsers (see JavaScript for detecting browser language preference), so I get the browser language from the server.
Python/Django: send request browser language as context parameter:
language = request.META.get('HTTP_ACCEPT_LANGUAGE')
return render(request, 'cssexy/index.html', { "language": language })
HTML: write it in a hidden input:
<input type="hidden" id="browserlanguage" value={{ language }}/>
JavaScript: get value of hidden input e.g. en-GB,en-US;q=0.8,en;q=0.6/ and then take the first language in the list only via replace and regular expression
const browserlanguage = document.getElementById("browserlanguage").value;
var defaultlang = browserlanguage.replace(/(\w{2}\-\w{2}),.*/, "$1");
JavaScript: convert to datetime and format it:
var options = { hour: "2-digit", minute: "2-digit" };
var dt = (new Date(str)).toLocaleDateString(defaultlang, options);
See: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
The result is (browser language is en-gb): 05/12/2016, 14:58
The best solution I've come across is to create [time display="llll" datetime="UTC TIME" /] Tags, and use javascript (jquery) to parse and display it relative to the user's time.
http://momentjs.com/ Moment.js
will display the time nicely.
You could use the following, which reports the timezone offset from GMT in minutes:
new Date().getTimezoneOffset();
Note :
- this function return a negative number.
getTimeZoneOffset() and toLocaleString are good for basic date work, but if you need real timezone support, look at mde's TimeZone.js.
There's a few more options discussed in the answer to this question
To convert date to local date use toLocaleDateString() method.
var date = (new Date(str)).toLocaleDateString(defaultlang, options);
To convert time to local time use toLocaleTimeString() method.
var time = (new Date(str)).toLocaleTimeString(defaultlang, options);
A very old question but perhaps this helps someone stumbling into this.
Below code formats an ISO8601 date string in a human-friendly format corresponding the user's time-zone and locale. Adapt as needed. For example: for your app, are the hours, minutes, seconds even significant to display to the user for dates more than 1 days, 1 week, 1 month, 1 year or whatever old?
Also depending on your application's implementation, don't forget to re-render periodically.
(In my code below at least every 24hours).
export const humanFriendlyDateStr = (iso8601) => {
// Examples (using Node.js):
// Get an ISO8601 date string using Date()
// > new Date()
// 2022-04-08T22:05:18.595Z
// If it was earlier today, just show the time:
// > humanFriendlyDateStr('2022-04-08T22:05:18.595Z')
// '3:05 PM'
// If it was during the past week, add the day:
// > humanFriendlyDateStr('2022-04-07T22:05:18.595Z')
// 'Thu 3:05 PM'
// If it was more than a week ago, add the date
// > humanFriendlyDateStr('2022-03-07T22:05:18.595Z')
// '3/7, 2:05 PM'
// If it was more than a year ago add the year
// > humanFriendlyDateStr('2021-03-07T22:05:18.595Z')
// '3/7/2021, 2:05 PM'
// If it's sometime in the future return the full date+time:
// > humanFriendlyDateStr('2023-03-07T22:05:18.595Z')
// '3/7/2023, 2:05 PM'
const datetime = new Date(Date.parse(iso8601))
const now = new Date()
const ageInDays = (now - datetime) / 86400000
let str
// more than 1 year old?
if (ageInDays > 365) {
str = datetime.toLocaleDateString([], {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
})
// more than 1 week old?
} else if (ageInDays > 7) {
str = datetime.toLocaleDateString([], {
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
})
// more than 1 day old?
} else if (ageInDays > 1) {
str = datetime.toLocaleDateString([], {
weekday: 'short',
hour: 'numeric',
minute: 'numeric',
})
// some time today?
} else if (ageInDays > 0) {
str = datetime.toLocaleTimeString([], {
timeStyle: 'short',
})
// in the future?
} else {
str = datetime.toLocaleDateString([], {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
})
}
return str
}
Inspired from: https://alexwlchan.net/2020/05/human-friendly-dates-in-javascript/
Tested using Node.js
Don't know how to do locale, but javascript is a client side technology.
usersLocalTime = new Date();
will have the client's time and date in it (as reported by their browser, and by extension the computer they are sitting at). It should be trivial to include the server's time in the response and do some simple math to guess-timate offset.

Categories