How to add translations to date using react-i18next? - reactjs

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

Related

Format date in react.js from data in api url

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)

Selecting date gives an object, not the dates

When I select dates and apply the filter, the startDate and endDate both are objects and i can't seem to be able to get the selected days.
I have already tried to select the attributes inside of the object, but it doesn't give me a good date.
I have the following code:
CONTROLLER
$scope.datePicker = {
date: {startDate: null, endDate: null},
options: {
maxSpan: {
days: 31
},
maxDate: moment(),
locale: {
separator: ' - ',
format: "D/MM/YYYY"
},
monthNames: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro',
'Outubro', 'Novembro', 'Dezembro'
]
}
};
HTML
<input class="filter-select date-picker" type="text"
date-range-picker
options="datePicker.options"
max="datePicker.options.maxDate"
ranges="datePicker.opstions.maxSpan.days"
ng-model="datePicker.date" />
I also have a watcher that logged the following image:
Does anyone knows how to get the the startDate and endDate values as a simple string or a Date format?
You can use moment to get the date with the format you expect.
For Example:
let startDate = moment($scope.datePicker.date.startDate).format("DD-MM-YYYY");
let endDate = moment($scope.datePicker.date.startDate).format("DD-MM-YYYY");
To know about various date formats you can check this on moment date formats

ChartJS: Translate x axis month to other languages

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.

Parsing from /Date(1487185200000)/ to date format

I want to convert this type of object to date format as (Sat 10/4/2016 5:03 PM)
how can I do that of input type /Date(1487185200000)/ using angularJs
May json is something like this
[{
"Post_Id": 1,
"Posts_Date":/Date(1487185200000)/,
"Post_Description": "Test",
},
{
"Post_Id": 2,
"Posts_Date": /Date(1487358000000)/,
"Post_Description": "Test",
}
]
This is my script in my controller
$http.post("/Home/GetPostData").then(function (d) {
$scope.Posts = d.data;
});
And this is my View
<div class="post_content" ng-repeat="p in Posts">
<h3> {{p.Post_Id}}</h3>
{{p.Post_Description}}
{{p.Posts_Date}}
</div>
And the output is somthing like this
1
Test
/Date(1487185200000)/
2
Test
/Date(1487358000000)/
want to convert my date as Standard format like (Sat 10/2/2016 4:50 PM) etc
If you are also interested in getting a Javascript Date (not just displaying), you can convert the JSON formmatted date/time information like this:
function parseJsonDate(jsonDateString){
return new Date(parseInt(jsonDateString.replace('/Date(', '')));
}
Credit
You need to visit this Angular Date filter
html
{{p.Posts_Date|removeBaces| date: 'medium'}}
js
myApp.filter('removeBaces', function() {
return function(input) {
return input.replace('/Date(','').replace(')/','');
}
});

Dynamically add filter in ng-repeat

I am building a table where the rows and columns are built entirely based on the data that is sent to it.
I'm very close to having it work, I'm having trouble figuring out how to build a custom filter and pass in the filter patterns dynamically
The object that makes up the columns looks like
{ name: 'transactionDate', displayName: 'Date / Time', displayOrder: 1, filter: "date: 'MM/dd/yy hh:mm a'" }
The object that makes up the transaction for the rows looks like this:
{ transactionDate: '2015-06-11', transactionType: 'This Type', transactionAmount: 25 }
The HTML I have is this:
<td ng-repeat="col in columns">{{transaction[col.name] | dynamicFilter: col.filter}}</td>
The filter I currently have built is:
function dynamicFilter($filter) {
return function (value, filter) {
console.log(filter);
console.log(value);
var test = $filter(filter)(value);
return test;
}
}
Both filter and value are getting passed correctly. I'm having trouble figuring out how to apply the filter to the value before returning. A value that might be passed in would 2015-06-10T16:17:14 be and a filter that would be passed in could be date: 'MM/dd/yy hh:mm a' to create date/time filter. Or 21 and currency for a dollar value.
I would like to be able to use Angular's built in features in a similar way you could on the view
For these dynamic filters that have partial params (such as the format you're providing with date), you have to remove the param from the filter and apply it later.
So filter: "date: 'MM/dd/yy hh:mm a'", needs to be just filter: "date".
The additional constraint, MM/dd/yy hh:mm a, would be sent along with the value $filter(filter)(value, 'MM/dd/yy hh:mm a');
To do this generically, you can take advantage of apply. The Object can be:
{filter: { type: "date", params: ['MM/dd/yy hh:mm a'] } }
And the directive can have (assuming you send the params as well):
var filterFn = $filter(filter.type);
return filterFn.apply(filterFn, [value].concat(filter.params));
EDIT: here's a JSFiddle with two buttons, the first demonstrates your original approach with "date: 'MM/dd/yy hh:mm a'", and the second demonstrates applied approach that I outline above http://jsfiddle.net/4whemakt/
You can apply and return the filtered value conditionally in your dynamicFilter. Something like this
function dynamicFilter($filter) {
return function (value, filter) {
if (filter.indexOf('date:') !== -1) {
//Note: I am using moment js to format the date
return moment(value).format(filter.match(/'([^']+)'/)[1]);
}
else {
return $filter(filter)(value)
}
}
}
moment.js reference http://momentjs.com/

Resources