I have a React application that fetches a list data that includes timestamps in ISO8601 format. The dates will come from US/Chicago time ex. "2020-09-01T06:05:00-05:00" ... I believe it's US/Chicago because the -05:00 representing central daylight savings. I'd like to have the option of the user selecting a timezone they want to see the dates in ( US/Chicago, US/Denver, ...etc ). I'd like to use the date-fns and date-fns-tz packages.
What is tripping me up is that when I print the date to the console I'll see the date in time in reference to my local timezone. Since I'll have users in different timezones I don't want that to be the default functionality, when I print dates and use them in the DOM they should reference the timezone they have selected.
type TZ = 'US/Chicago' | 'US/Denver';
const [timezone, setTimezone] = React.useState<TZ>('US/Chicago');
const onUpload = (data: string[]) => {
// convert data ( list of iso8601 dates ) to tz
const dates = data.map(d => parseISO(d));
// something with date-fns-tz
setDates(dates)
}
this might do the trick:
const clientsTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone
const [timezone, setTimezone] = React.useState(clientsTimeZone);
or if that has SSR problems, u could set it in useEffect
Related
I'm working on a forum and using a form that the user fills out I'm storing data as an object inside an array. The data I'm storing includes the title of a topic, the message, the author and the date. That data is stored inside a topic array which I'm mapping on screen so the user can see all current topics, who created them and the date in which they were created. I also started to use localStorage so I can save my data and test to make sure everything looks good after my page refreshes.
const [topic, setTopic] = useState(() => {
const topicJson = localStorage.getItem("topic");
return topicJson ? JSON.parse(topicJson) : [];
});
const updatedTopic = [
...topic,
{
title: title,
message,
author: "Dagger",
date: new Date(),
},
];
setTopic(updatedTopic);
};
That's the code that I'm using which works as intended however when I map through the array to post the data on screen, I'm having trouble with showing the date. I'm using date-fns because it displays the date exactly how I want it.
Example: 2/19 9:39PM. That's how I want the date to look on screen and using date-fns has been the only thing I've found that makes it look that way.
{topic
.sort((a, b) => b.date - a.date)
.map(({ date }, index) => (
<tr>
{<td>{format(date, "M/dd h:mma")}</td>}
</tr>
))}
That's the code I'm using to map through the array to show the date. Before adding localStorage it worked fine. When I remove the format and show the code as date it works but including format gives me this error:
throw new RangeError('Invalid time value');
// Convert the date in system timezone to the same date in UTC+00:00 timezone.
// This ensures that when UTC functions will be implemented, locales will be compatible with them.
I think your are using Date object to store date and JSON.stringify cant handle Date object. You should to use Date method.
Easy way just save not Date object but ISO string.
date.toISOString()
And in table:
{<td>{format(parseISO(date), "M/dd h:mma")}</td>}
Is it possible to format the date from date-fns based on the users devices date format?
for example my provided code always will show 04/29/2023 on any device, but for some users they would prefer format to show that is set in their device, for example 29/04/2023. How to show the date format depending on the users devices date formats?
<Text>
{format(date, "P")}
</Text>
You can use the Intl object from JavaScript to format dates according to the user's device locale. Here's an example of how you can use it in React Native:
const App = ({ date }) => {
const formattedDate = new Intl.DateTimeFormat(undefined).format(date);
return <Text>{formattedDate}</Text>;
};
I want to modify the visible range showed in the agenda view so it includes all the days from the current month only, so far this is my attempt:
const Scheduler = () => {
const [currentDate, setCurrentDate] = useState(new Date())
const onNavigate = newDate => {
const d = new Date(newDate.getFullYear(), newDate.getMonth(), 1);
setCurrentDate(d)
}
return (
<Calendar
onNavigate={onNavigate}
date={currentDate}
/>
)
}
So because per default the length prop is set to 30 to accomplish my goal I just need to set the day of date prop to always be first one, this is why inside onNavigate function I create a new Date object (called d in my code) in which I basically copy the Date object being received by the function but set its day to 1.
This works only the first time I click the next button, if I attempt to go to future months nothing happens and when I log the Date object received by the function(newDate in the code) it changes only the first time the function is called but after that the Date it receives is always the same one.
This happens only for the agenda view and only when going to future months.
I can go just fine to past months in the agenda view and in the calendar view I can go to future and past months without problems.
PD: I omited unnecessary props like events, localizer... etc because I think they are not relevant as the calendar works fine is just this functionality I'm trying to change that is not working as expected.
I am working on a React JS project where my state is getting updated with date object string from the backend JSON response. I am getting a Date Time object in form of a string which looks like this:
createDateTime: "2022-02-08T14:17:44"
The "createDateTime" object is assigned to my react js state, but when I show that updated state in the Browser UI, I get this:
2022-02-08T14:17:44
I want to display just the date, not the time stamp that comes along with the JSON string response. Is there any method that I can use to display just the Date?
2022-02-08
I would create some helpers to show exactly what you need. How about something like this?
function DateTimeParser(date?: string) {
if (date === undefined) return date;
const dateTime = new Date(date);
const parsedDate = `${dateTime.getDate()} ${
dateTime.getMonth()
} ${dateTime.getFullYear()}`;
return parsedDate;
You can amend this to show exactly what you need.
Calling toLocaleDateString on your date value should get the result you want but first of all, you will need to parse the date you get from the server:
const parsedDate = new Date(responseDate)
const date = parsedDate.toLocaleDateString()
You can optionally pass to toLocaleDateString() the desired locale (in case you want to get the date in the format which differs from your local one)
How can I set the time zone globally in react? Is it possible? I know the new Date() of javascript actually gives the time zone of the system. But I want to set the time zone in one file in react application and re use it. And when I will change the time, the time will also be changed according to the specific time zone. Thanks in advance.
Hey this is not a react related question, I would say more of a JS question but what I normally do is to use Luxon, you need to install the library an afterwards what I do is this:
// src/utils/luxon/index.ts
import {DateTime, Settings} from 'luxon'
// Example to set EST as the default timezone in the app.
Settings.defaultZoneName = 'America/New_York'
export {DateTime, Settings}
Then I just import that utils file and use the DateTime object to parse and handle dates.
So if you have lets say for example an epoch date you can parse it like this
import {DateTime} from 'utils/luxon'
const epochDate = 1597354080
const luxonDate = DateTime.fromSeconds(epochReleaseDate)
console.log(luxonDate.toLocaleString(DateTime.TIME_SIMPLE))
If you click this page you will notice that the current est time for that epoch should return Thursday August 13, 2020 17:28:00 (pm)
You can parse those dates to Javascript date objects but I suggest you to get used to luxon because it makes working with dates pretty easy. Just remember that the Date returned by luxon is way different than the Js Date object so don't combine them, instead use the parsing methods of luxon to convert a Js Date to Luxon Date and vice versa
I actually tried to solve the problem this way. to initialize the date in the ui I called the getGlobalDate function instead of calling new Date() in js. And for changing the date I passed the date object to onChangeFormat function and convert the date time.
export const language = "en-US";
export const timeZone = { timeZone: "Pacific/Auckland" };
//to initialize the date
export function getGlobalDate() {
return new Date().toLocaleString(language, timeZone);
}
//for onChanging the date and convert it to the timzone
export function onChangeFormat(e) {
const convertToUTC = e.toLocaleString(language, timeZone);
console.log(convertToUTC);
return convertToUTC;
}