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)
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>}
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;
}
I'm using gatsby-source-contentful where I have a type called ContentfulBlogPost, whose schema looks something like this:
{
id
title
body
date
}
Date is a string (in YYYY-MM-DD format), auto-magically handled by Gatsby's data layer as a Moment object; I can call fromNow and formatString on it and all that.
What I want is to use GraphQL to query for a list of posts from a given year, based on that date field.
If I do this:
{
allContentfulBlogPost(
filter: { date: { regex: "/^2017/" } }
) {
...
}
}
then I get this error: "Cannot read property 'fromNow' of undefined"
What I really want is to be able to filter the allContentfulBlogPost data set by date, either by transforming the date into an integer/string year and finding on that, or by asking for all items whose date falls between Jan 1 and Dec 31 of the given year.
Right now, I have a query running in gatsby-node that pulls in all blog posts, then groups them by year in JS and then passes the array of posts into a template. This works, but it really seems like there should be a GraphQL way of doing this?
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 have Datetime in my sqldb when im fetching data from database using Json formatted im Getting Datetime as a "/Date(820434600000)/"
Here im having some code which i copied from stackoverflow but not working please Guide me
app.filter("DateFilter", function () {
var re = /\/Date\(([0-9]*)\)\//;
return function (x) {
var m = x.match(re);
if (m) return new Date(parseInt(m[1]));
else return null;
};
});
<td>{{eee.DataofJoin | DateFilter | date: 'yyyy-MM-dd HH:mm'}}</td>
So you are getting from database a instance of Date object, so if you bind the
date to new Date got from DB as follows:
$scope.date = new Date(820434600000);
(will result in this "1995-12-31T18:30:00.000Z") and using angular filters for date you can display in any format you want;
In HTML you do this:
<p>{{date | date: 'yyyy-MM-dd HH:mm'}}</p>
This will result in displaying
1995-12-31 20:30
Angular takes care of that with built-in filters, no need for custom one. Though it's not best practice what you do, try using only the timestamp stored in DB.