I am trying to format my date in React/ typescript project, however the data is from an api, so I can map over the data and display it but how do I convert it to a format like '22 June 2021'?
The data from the api is in format:
{
"title": 'First',
"time": "2020-07-22T13:22:10.2566789+00:00",
}
Then I am binding to the template as {data.time}
Any idea's?
Yes, it is a simple way to achieve that
const date = new Date("2020-07-22T13:22:10.2566789+00:00")
const formattedDate = date.toLocaleDateString("en-GB", {
day: "numeric",
month: "long",
year: "numeric"
})
console.log(formattedDate)
PackageName: npm i moment
Install the moment npm.
"moment" is an npm package. After installation import the package
import moment from 'moment'
Next, Convert the data like this:
"time": "2020-07-22T13:22:10.2566789+00:00"
moment(time).format('DD/MM/YYYY HH:mm')
For Example, if your code is like this:
var objName = {
"title": 'First',
"time": "2020-07-22T13:22:10.2566789+00:00",
}
This is how you can implement the new Time Format (Dont forget to npm install and import moment.js)
let formattedTime = moment(objName.time).format('DD/MM/YYYY HH:mm');
console.log(formattedTime);
DateFns it is a light library, so I can recommend it.
import format from 'date-fns/format'
const formattedDate = format(
new Date('2020-07-22T13:22:10.2566789+00:00'),
'dd MMMM yyyy'
)
console.log(formattedDate)
Related
I have react component where I am using useMemo to define table structure. My data is coming via API in DateTime (Web API C#). I tried to use moment to convert date Time format but unable to do so.
current time format without moment 2020-12-18T14:00:00
const scheduleColumns = useMemo(
() => [
{
Header: "Site ID",
accessor: "siteId",
},
{
Header: "Start Time",
accessor: moment("startTime").fromNow(),
},
],
[]
);
..Table
<TableItemsTabs
apiUrl={api.myAPI}
columns={scheduleColumns}
></TableItemsTabs>}
Even found more simpler solution, doesn't even need any module
let a = new Date('2020-12-18T14:00:00');
a.toLocaleString('en-GB');
// Output - "18/12/2020, 14:00:00"
i use react-native calendars which config the moment like so:
LocaleConfig.locales["he"] = {
monthNames: [
"ינואר",
"פברואר",
"מרץ",
"אפריל",
"מאי",
"יוני",
"יולי",
"אוגוסט",
"ספטמבר",
"אוקטובר",
"נובמבר",
"דצמבר",
],
monthNamesShort: ["ינו", "פבר", "מרץ", "אפ", "מאי", "יוני", "יולי", "אוג", "ספט", "אוק", "נוב", "דצמ"],
dayNames: ["ראשון", "שני", "שלישי", "רביעי", "חמישי", "שישי", "שבת"],
dayNamesShort: ["א", "ב", "ג", "ד", "ה", "ו", "ש"],
today: "היום",
};
LocaleConfig.defaultLocale = "he";
and also i use moment in my components and i want to config the dates like :
moment.updateLocale('he', {
longDateFormat : {
LT : 'HH:mm',
LTS : 'HH:mm:ss',
L : 'DD/MM/YYYY',
LL : 'D MMMM YYYY',
LLL : 'D MMMM YYYY HH:mm',
LLLL : 'dddd D MMMM YYYY HH:mm'
}..........................
my problem i dont know how to decalre it one time and just import it to every component that i need (because i have many component that i need to use it)
the question how i can declare it one time and just import it with one line.
because right now i have to put all the long code(that above) in every component
(i build my app with mern react native)
If you want to change moment globally then please have a look on "https://www.npmjs.com/package/moment-timezone". Here you will find global timezone set methods.
I am using react-i18next for the first time and I want to translate the string of date format. how can I do it using react-i18next?
this is the format the date is in
Sat Jul 27 2019 00:00:00 GMT+0300
how do I translate it into another language?
could someone help me with this? thanks.
You can format a date like so in your translations
"key": "Current date: {{date, dd/MM/yyyy}}"
Have a look at the i18next official docs about formatting.
You can initialise i18next providing a function for interpolation, like so;
i18next.init({
interpolation: {
formatSeparator: ',',
format: function(value, formatting, lng){
if(value instanceof Date) return moment(value).format(formatting);
return value.toString();
}
}
});
The result:
i18next.t('key', { date: new Date() }); // -> Current date: 13/07/2019
source: https://github.com/i18next/i18next/issues/774#issuecomment-232396505
So I'm using the BlueprintJS datetime package in a React project to render a birthday picker and I want to set the months names of the select to the Spanish version. In their documentation says they use react-day-picker in order to render the calendar and from the react-day-picker documentation there's a parameter to set the months names from an array but I don't get it to change the select names. This is what I've set in the component. The weekdaysLong and weekdaysShort works fine but not the months property.
<DateInput
formatDate={date => date.toLocaleString('es-ES', {year: "numeric", month: "2-digit", day: "numeric"})}
onChange={this.handleDateChange}
parseDate => new Date(str)}
placeholder={"DD/MM/YYYY"}
maxDate={now}
minDate={minDate}
value={this.state.date}
dayPickerProps={{
locale: 'es',
months: DateFormatString.months,
weekdaysLong: DateFormatString.weekDaysLong,
weekdaysShort: DateFormatString.weekDaysShort,
firstDayOfWeek: 1,
}}
/>
And this is the variable where I have the months and weekdays
const DateFormatString = {
months: [
'Enero',
'Febrero',
'Marzo',
'Abril',
'Mayo',
'Junio',
'Julio',
'Agosto',
'Septiembre',
'Octubre',
'Noviembre',
'Diciembre'
],
weekDaysLong: [
'Domingo',
'Lunes',
'Martes',
'Miercoles',
'Jueves',
'Viernes',
'Sabado'
],
weekDaysShort: [
'Do',
'Lu',
'Ma',
'Mi',
'Ju',
'Vi',
'Sa'
]
}
Anyone have an idea what is happening or know another way to set the whole component's language?
It seems to be a recently opened (and soon fixed) issue as per this github issue page: https://github.com/palantir/blueprint/issues/3265
Either you can wait for a fix to be merged (and then update your package.json to use the new version), or you must use some other library. Hope that helps!
I'm having difficulties in finding out how to translate the time axis. I'm using MMM YYYY for time displayFormats in xAxes.
It always displays date like May 2018. Does anyone know how to localize here?
For example, if the language is french, the month should be displayed as Mai instead of May. I searched everywhere, only find someone said it is possible to do that using time.parser, but I am not sure how to do that.
Any suggestions would be appreciated.
I was struggling with the same problem in my Ruby on Rails application.
We don't use angularjs, but I think the way of using Chart.js is very similar.
I will post the way I managed it to work in Ruby on Rails and polish locale. But you should be able to easy customize the solution to work with Angular.js
Include moment.js locale in the JavaScript bundle apart of moment.js library
//= require moment
//= require moment/pl.js
Add custom displayFormats to make it easier to parse date in callback function. And add callback function to parse and format date again.
options: {
...
scales: {
xAxes: [{
type: 'time',
time: {
displayFormats: {
'hour': 'HH:mm',
'day': 'DD-MM-YYYY',
'week': 'DD-MM-YYYY',
'month': 'DD-MM-YYYY',
},
unit: '<%= #report.scale %>',
},
ticks: {
callback: function(value, index) {
let displayFormats = {
'hour': 'HH:mm',
'day': 'DD-MM-YYYY',
'week': 'YYYY WW',
'month': 'MMMM YYYY',
};
let unit = '<%= #report.scale %>';
let format = displayFormats[unit];
return moment(value, 'DD-MM-YYYY').format(format, value);
}
}
}],
For some reason moment.js inside of Chart.js ignores locales. But when calling moment.js again inside of the callback function it works well.
I added guard return for all units other than month. I didn't want to reparse and reformat dates other than months.