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;
}
Related
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)
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
const dataToPush = {
firstName: seniorfirstName,
lastName: seniorlastName,
familyMember: userid,
birthdate: date
}
var k = dbSeniors.push(dataToPush);
In this code, I'm basically trying to store a date which has been declared like:
import DatePicker from "react-datepicker";
And:
const [date, setDate]=useState(new Date());
Moreover, whenever I print to console, then date is indeed what I choose, in this case:
Wed Mar 11 2020 22:13:56 GMT+0530 (India Standard Time).
However, whenever I go to firebase than the date key, value pair has not been pushed at all!
Also, when I tried converting the Date object toString using the toString(date) function, I just got "[object Undefined]".
I think you use the toString in the wrong way, you should use it like this :
date.toString()
instead of toString(date)
The other solution is to store the date as a timestamp in firebase :
firebase.firestore.Timestamp.fromDate(date).toDate());
I have a calendar on my ionic app and there is an API that brings me events from database.
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://portalemme2.com.br/SaoJoseAPI/agenda', true);
this.http.get('http://portalemme2.com.br/SaoJoseAPI/agenda').map(res => res.json()).subscribe(vetor => {
this.eventos = vetor.eventos;
});
How can I change the date format to appear on calendar?
Every event has an date like '2018-01-01' and an hour like '01:00:00.0000000' (from database)
But the calendar from ionic only accepts date in this format '2017-12-16 01:00:00'
I need to transform all dates to push in "this.eventos" array.
You can use moment.js, an excellent and easy to use library to manipulate dates. You should use data returned from the server to construct a Moment object pasing them to the moment() function and then, use format method to convert date to the format required by Calendar. In your case, to convert to these format, you should pass to format method something like "YYYY-MM-DD HH:MM:SS".
I'm using Moment.js with react-datepicker. It works as intended in terms of the date transformation to ISO-8601, but I can't get it compliant with the time.
Here's my component:
Stated initially:
this.state = {
from: moment().subtract(7, "days"), // Default 1 week back
to: moment(), // Current date
};
The component itself:
<DatePicker
dateFormat="DD-MMM HH:mm"
dropdownMode="select"
selected={this.state.from}
onChange={this.handleFromChange}
/>
And the onchange trigger:
handleFromChange(date) {
this.setState({
from : date
});
}
I think my issue is the dateFormat; The DD-MMM are easily transformed to ISO-8601 by calling using the ECMAScript function toISOString() before posting it to some backend services. But how do I get the time to go with it?
The user(myself, testing) can chance the time on the datepicker itself, but it won't register in the state. Simply it will just pick the current time, or current time 1 week ago(as per the moment from/to initial states). The date, i can change also, but the time remains the same(current time).
How do I change the dateFormat so it takes the time input from the user? How do I make it ISO 8601 compliant per default in the dateFormat attribute?
Edit: I just tested with setting "from" to subtract 5 minutes at such:
this.state = {
from: moment().subtract(5, "minutes"),
to: moment(), // Current date
};
And it formats it correctly when I post it. Seems strange. It must be related to the onChange function then?
Try using dateFormat="dd-MMM hh:mm" and change onChange function to this to avoid error.
handleFromChange(date) {
this.setState({
from : date || ""
});
}