Can use react-admin DateInput to change the format like dd/MM/yyyy to MM/dd/yyyy - react-admin

The component
<DateInput
options={{ format: "MM/DD/YYYY", clearable: true }}
className="location-input" label="Purchase Date" source="PurchaseDate"
validate={validatePurchaseDate}
/>

From the doc, you can format the input/output of the component using the format and parse exposed method:
const dateFormatter = v => {
// v is a `Date` object
if (!(v instanceof Date) || isNaN(v)) return;
const pad = '00';
const yy = v.getFullYear().toString();
const mm = (v.getMonth() + 1).toString();
const dd = v.getDate().toString();
return `${yy}-${(pad + mm).slice(-2)}-${(pad + dd).slice(-2)}`;
};
const dateParser = v => {
// v is a string of "YYYY-MM-DD" format
const match = /(\d{4})-(\d{2})-(\d{2})/.exec(v);
if (match === null) return;
const d = new Date(match[1], parseInt(match[2], 10) - 1, match[3]);
if (isNaN(d)) return;
return d;
};
<DateInput source="isodate" format={dateFormatter} parse={dateParser} />
Reference: https://marmelab.com/react-admin/Inputs.html#transforming-input-value-tofrom-record

If this is the exact and only change you are after - you can use the locale setting with the follwoing values:
"en-US": MM/dd/yyyy
"en-GB": dd/MM/yyyy
It's kind of a hack but also a painless easy solution.

Related

disable sunday on react-native-calendar-picker react native

I want to disable sunday in react-native-calendar-picker. Here what i have done, but not worked yet
const disableDate = () => {
let date = new Date()
return date.getDay() == 0 ? true : false
}
and in the calendar
<CalendarPicker
minDate={minimalDate()}
initialDate={new Date()}
disabledDates={disableDate()}
onDateChange={(res) => setSelectedDate(moment(res).format("D MMMM YYYY"))}
/>
You should pass date as a parameter to your function Try this,
const disableDate = (date) => {
return date.getDay() === 0;
}

Async Storage from package "#react-native-community/async-storage" not retrieving date properly in react-native

I have the following code in react native:
const handleRefresh = useCallback(async () => {
const date = await AsyncStorage.getItem(`lastRequestDate`);
console.log('date: ', date);
console.log('type of: ', typeof date === 'string' ? date : '');
const previousDate = new Date(typeof date === 'string' ? date : '');
// const previousDate = new Date('2021-06-02T00:52:46.892Z');
console.log('previous date: ', previousDate);
}, [user]);
When I console log previousDate I get Date { NaN } but if I console log date I get "2021-06-02T00:52:46.892Z". If I console log const previousDate = new Date('2021-06-02T00:52:46.892Z'); I get the correct date. However if I replace the string by date variable the error appears (Date { NaN }) (const previousDate = new Date(typeof date === 'string' ? date : '');)
Try to save the condition in a variable and use that in the new Date(...)
const newDate = typeof date === 'string' ? date : ''
const previousDate = new Date(newDate);

Use filter in Vue3 but can't read globalProperties

Just a quick question,
I know that Vue3 doesn't use filters anymore and notes says use computed or methd instead. but also there is a globalProperties we can use,
I used this globalProperties but keep getting this error
Uncaught TypeError: Cannot read property 'globalProperties' of undefined
Does anyone know where is the bug in my code?
const app = {
data() {
return {
message: ""
}
}
}
app.config.globalProperties.$filters = {
formatDate(value) {
if (value == "0001-01-01T00:00:00")
return "";
var today = new Date(value);
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = dd + '/' + mm + '/' + yyyy;
return today;
}
}
Vue.createApp(app).mount('#app');
And I am using the filter in my table like this
<td>
{{ $filters.formatDate(incident.incidentData) }}
</td>
The config field belongs to the root instance not to the root component so you should do:
const app = {
data() {
return {
message: ""
}
}
}
const myApp=Vue.createApp(app)
myApp.config.globalProperties.$filters = {
formatDate(value) {
if (value == "0001-01-01T00:00:00")
return "";
var today = new Date(value);
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = dd + '/' + mm + '/' + yyyy;
return today;
}
}
myApp.mount('#app');
Vue.createApp(app) return the root instance
myApp.mount('#app'); after mounting root app to an element it returns the root component

How do you format a number to currency when using React native Expo?

How do I take a number like 10000 and have it output as $10,000.00?
I even had a problem with String.format(...) with a Not a function error.
I followed numerous articles, all incomplete and none working. I don't need full internationalization, just the ability to format a number
You can use toFixed method for showing 2 decimal point.
let num = 1000;
console.log(num.toFixed(2)); // 1000.00
And you can use Regex like this
function currencyFormat(num) {
return '$' + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}
console.log(currencyFormat(2665)); // $2,665.00
You can use this library react-number-format. It has these features
Prefix, suffix and thousand separator.
Custom format pattern.
Masking.
Custom formatting handler.
Format number in an input or
format as a simple text
Sample usage
<NumberFormat value={2456981} displayType={'text'} thousandSeparator={true} prefix={'$'} />
Output : $2,456,981
Edit: Sorry -this is a React.js solution - not React Native.
None of the above worked for me ... but this chap had the right idea / solution https://medium.com/#nidhinkumar/react-js-number-format-and-styling-a1a6e211e629
const numberFormat = (value) =>
new Intl.NumberFormat('en-IN', {
style: 'currency',
currency: 'INR'
}).format(value);
numberFormat(50000); //output as ₹ 50,000.00
numberFormat(10000); //output as ₹ 10,000.00
To avoid using libraries, you can use the following code
const defaultOptions = {
significantDigits: 2,
thousandsSeparator: ',',
decimalSeparator: '.',
symbol: '$'
}
const currencyFormatter = (value, options) => {
if (typeof value !== 'number') value = 0.0
options = { ...defaultOptions, ...options }
value = value.toFixed(options.significantDigits)
const [currency, decimal] = value.split('.')
return `${options.symbol} ${currency.replace(
/\B(?=(\d{3})+(?!\d))/g,
options.thousandsSeparator
)}${options.decimalSeparator}${decimal}`
}
The fastest way is to use react-number-format, as stated above, but don't forget the renderText prop so that React Native don't throw rendering error.
Follow this step:
Install. Use this command:
npm i react-number-format
Use it in your React Native app like this:
import React from 'react';
import NumberFormat from 'react-number-format';
export function ReactNativeNumberFormat({ value }) {
return (
<NumberFormat
value={value}
displayType={'text'}
thousandSeparator={true}
prefix={'$'}
renderText={formattedValue => <Text>{formattedValue}</Text>} // <--- Don't forget this!
/>
);
}
It's working good. As you can see, I ended up creating my custom component that accept value as prop so I can use it everywhere I need it. Just like this:
<View>
<ReactNativeNumberFormat value={530000} />
</View>
Hope can be useful.
PS: This is my reference => https://github.com/s-yadav/react-number-format/issues/17#issuecomment-395187806.
Use toLocaleString native React function:
const formatNumber = (q) => {
return q.toLocaleString('en-US', {
style: 'currency',
currency: 'USD'
})
}
I wrote the following number format utility recently which can be used in OP's case as well as others. It should hopefully be fairly straightforward to amend it to cover other cases (I expect most would like to change my default values for example).
type NumberFormatProps = {
value: number;
thousandSeparator?: string;
decimalSeparator?: string;
significantDigits?: number;
showTrailingZeros?: boolean;
symbol?: '$' | 'kr.' | '%'; // Add other symbols as needed
showSymbol?: boolean;
symbolPosition?: 'before' | 'after';
showSymbolSpace?: boolean;
};
/**
* Formats a number. Supports changing symbol, thousand and decimal separators and more (see props).
* #param value The value to format
* #param thousandSeparator The separator to use between thousands
* #param decimalSeparator The separator to use before decimals
* #param significantDigits The number of significant digits to show
* #param showTrailingZeros Whether to show trailing zeros for significant digits (i.e. 1,00 if significant digits is 2)
* #param symbol The symbol to use
* #param showSymbol Whether to show the symbol
* #param symbolPosition Whether to show the symbol before or after the value
* #param showSymbolSpace Whether to show a space between the symbol and the value
* #returns
*/
export const getFormattedNumber = ({
value,
thousandSeparator = '.',
decimalSeparator = ',',
significantDigits = 0,
showTrailingZeros = false,
symbol = 'kr.',
showSymbol = true,
symbolPosition = 'after',
showSymbolSpace = true,
}: NumberFormatProps) => {
const significantDigitsExponent = 10 ** significantDigits;
const valueWithSignificantDigits = showTrailingZeros
? // If significant digits is 2 then this is e.g. 1.00, 1.10, 1.11
value.toFixed(significantDigits)
: // If significant digits is 2 then this is e.g. 1, 1.1, 1.11
`${Math.round((value + Number.EPSILON) * significantDigitsExponent) / significantDigitsExponent}`;
// Split the value into the parts before and after the decimal point
const [integerPart, fractionalPart] = valueWithSignificantDigits.toString().split('.');
// Replace thousand separator in integer part
const formattedIntegerPart = `${integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator)}`;
// Add decimal separator and fractional part if needed
const formattedValue = fractionalPart
? `${formattedIntegerPart}${decimalSeparator}${fractionalPart}`
: formattedIntegerPart;
// Add symbol
if (showSymbol && Boolean(symbol)) {
const formattedValueWithSymbol =
symbolPosition === 'after' ? `${formattedValue} ${symbol}` : `${symbol} ${formattedValue}`;
return showSymbolSpace ? formattedValueWithSymbol : formattedValueWithSymbol.replace(' ', '');
}
return formattedValue;
};
In OP's case this would be called like so:
getFormattedNumber({
value: 10000,
thousandSeparator: ',',
decimalSeparator: '.',
symbol: "$",
showSymbolSpace: false,
symbolPosition: 'before',
significantDigits: 2,
showTrailingZeros: true
})
export const CurrencyFormatter = (number, options) => {
const defaultOptions = {
significantDigits: 2,
thousandsSeparator: ",",
decimalSeparator: ".",
symbol: "$",
};
const currencyFormatter = (value, options) => {
if (typeof value !== "number") value = 0.0;
options = { ...defaultOptions, ...options };
value = value.toFixed(options.significantDigits);
let valueFormatted;
if (options.significantDigits == 0) {
const [currency] = value.split(".");
valueFormatted = `${options.symbol}${currency.replace(
/\B(?=(\d{3})+(?!\d))/g,
newOptions.thousandsSeparator
)}`;
} else {
const [currency, decimal] = value.split(".");
valueFormatted = `${options.symbol}${currency.replace(
/\B(?=(\d{3})+(?!\d))/g,
options.thousandsSeparator
)}${options.decimalSeparator}${decimal}`;
}
return valueFormatted;
};
return currencyFormatter(number, options);
};
could be achieved as shown below, and you could also remove trailing 00 at the end if there is no decimals
costing= () => {
const cost= 1478.90 + 940;
return parseFloat(cost).toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
}

TypeError: expected dynamic type 'double' but had type 'string'

I'm running into this error when trying to use datePickerAndroid and setting the state afterwards.
Error Message
I feel like the problem may be from the initial state being a new Date() but not 100% sure.
_isAndroid = async () => {
let {action, year, month, day} = await DatePickerAndroid.open({
date: this.props.startDate,
});
if (action === DatePickerAndroid.dismissedAction) {
this.props.closeModal()
} else {
const date = year + "-" + month + "-" + day
this.props.onDateChange(date)
}
}
Prop Function:
onDateChange = (newDate) => {
this.setState({currentDate: newDate}) // <- This one is breaking
let dates = this.state.dates;
let index = this.state.currentIndex;
if (this.state.currentKey === "start") {
dates[index].start = newDate
} else {
dates[index].end = newDate
}
this.setState({dates: dates});
}
I've narrowed it down to the first setState, and I've tried making the initial state a string as well as setting the state to a simple string but still getting the error.
For DatePickerAndroid
expected dynamic type double
In other words native component wants time, but you put string. You this.props.startDate is string, transfer time in time format. Example:
const {action, year, month, day} = await DatePickerAndroid.open({
date: new Date() // <- This is Date, not string!
});
Good luck!