How to format Yup date() to brazilian format? - yup

I'm wanting to use yup to validate an input, that is being used as Birthday. By first I added the simple .date() function to the yup shaped object, but it won't accept Brazilian dates, as the format is same as European (dd/MM/YYYY), how do I proceed?

Use .transform() to parse your value with a function passing the following parameters:
value as current Date parsed by yup.
originalValue as the original inputted value (e.g. "01/01/2022").
yup.date().transform((value, originalValue) => {
// Do your parsing structure
return newValue
})
Remember that your newValue must be a Date object since you want to validate a yup.date() type in your form.
You can use this example as solution for you to parse your value to "dd/MM/YYYY" format:
// Input: '10/12/2022'
// yup.object({ [...]
birthday: yup.date().transform((value, originalValue) => {
// originalValue = "10/12/2022"
try {
let date = originalValue.split('/')
// date = ["10", "12", "2022"] <- day, month and year respectively
if (date.length === 3) {
let newDate = `${date[2]}-${date[1]}-${date[0]}`
return new Date(newDate)
}
return null
} catch (e) {
return null
}
}),
// [...] })
// Expected Output: '2022-10-12T00:00:00.000Z'
See yup docs about parsing values using .transform(): Yup Schema Basics - Parsing: Transforms

Related

Neatly parsing a date in "MMddyy" format along with other formats in dart

I guess it is not possible to parse a date in "MMddyy" format in dart.
void main() {
String strcandidate = "031623";
String format = "MMddyy";
var originalFormat = DateFormat(format).parse(strcandidate);
}
Output:
Uncaught Error: FormatException: Trying to read dd from 031623 at position 6
The following works fine when parsing a date in "MM-dd-yy" format.
void main() {
String strcandidate = "03-16-23";
String format = "MM-dd-yy";
var originalFormat = DateFormat(format).parse(strcandidate);
}
In the problem, the input date string can be in any format e.g ['yyyy-MM-dd', 'MMM'-yyyy, 'MM/dd/yy']. I am parsing the input string for these formats in a loop as follows.
dateFormatsList = ['yyyy-MM-dd', 'MMM'-yyyy, 'MM/dd/yy'];
for (String format in dateFormatsList ) {
try {
originalFormat = DateFormat(format).parse(strcandidate);
dateFound = true;
} catch (e) {}
}
Adding 'MMddyy' to dateFormatsList is not going to work.
But regular expression be used to parse this format.
However if all formats are parsed using parse method and one additional format is parsed using regular expression, then the code is not that neat, and cluttered.
To write as much neat and efficient code as possible, if you want, you can share your insights about any possibility for making it efficient and clean while incorporating 'MMddyy'format. Tysm!
See How do I convert a date/time string to a DateTime object in Dart? for how to parse various date/time strings to DateTime objects.
If you need to mix approaches, you can provide a unified interface. Instead of using a List<String> for your list of formats, you can use a List<DateTime Function(String)>:
import 'package:intl/intl.dart';
/// Parses a [DateTime] from [dateTimeString] using a [RegExp].
///
/// [re] must have named groups with names `year`, `month`, and `day`.
DateTime parseDateFromRegExp(RegExp re, String dateTimeString) {
var match = re.firstMatch(dateTimeString);
if (match == null) {
throw FormatException('Failed to parse: $dateTimeString');
}
var year = match.namedGroup('year');
var month = match.namedGroup('month');
var day = match.namedGroup('day');
if (year == null || month == null || day == null) {
throw ArgumentError('Regular expression is malformed');
}
// In case we're parsing a two-digit year format, instead of
// parsing the strings ourselves, reparse it with [DateFormat] so that it can
// apply its -80/+20 rule.
//
// [DateFormat.parse] doesn't work without separators, which is why we
// can't use directly on the original string. See:
// https://github.com/dart-lang/intl/issues/210
return DateFormat('yy-MM-dd').parse('$year-$month-$day');
}
typedef DateParser = DateTime Function(String);
DateParser dateParserFromRegExp(String rePattern) =>
(string) => parseDateFromRegExp(RegExp(rePattern), string);
var parserList = [
DateFormat('yyyy-MM-dd').parse,
DateFormat('MMM-yyyy').parse,
DateFormat('MM/dd/yy').parse,
dateParserFromRegExp(
r'^(?<month>\d{2})(?<day>\d{2})(?<year>\d{4})$',
)
];
void main() {
var strcandidate = '12311776';
DateTime? originalFormat;
for (var tryParse in parserList) {
try {
originalFormat = tryParse(strcandidate);
break;
} on Exception {
// Try the next format.
}
}
print(originalFormat);
}
I think it's a bit hacky but what about use a regular expression (RegExp) to parse the date divider and then replace it with just ""?
void main() {
String strcandidate = "031623";
String strYear = strcandidate.substring(4);
//Taken 20 as the year like 2023 as year is in 2 digits
String _newDateTime = '20' + strYear + strcandidate.substring(0, 4);
var _originalFormat = DateTime.parse(_newDateTime);
print(_originalFormat);
}
add the intl to yaml then write this code:
import 'package:intl/intl.dart';
void main() {
var strcandidate = DateTime(2023, 3, 16);
String format = "MMddyy";
var originalFormat = DateFormat(format).format(strcandidate);
print(originalFormat);
}

Swift Playground : How do I write a while function which doubles each day?

I need to create a loop which will show pennies each day and total for the months end. I couldn't create the loop as the playground keeps on multiplying infinitely.
Great question! There are definitely a lot of ways to solve this problem, but if I understand your question - this is how I would solve it.
Step 1 - Date Extension
First, I would start by making an extension to Date.
extension Date {
/// The month component of the provided date.
var month: Int {
return Calendar.current.component(.month, from: self)
}
/// Exactly one day before the provided date.
var prevDay: Date {
return Calendar.current.date(byAdding: .day, value: -1, to: self)!
}
/// Exactly one day after the provided date.
var nextDay: Date {
return Calendar.current.date(byAdding: .day, value: 1, to: self)!
}
}
These variables will make some of the later work, easier.
Step 2 - Variables
Then we can setup the variables.
First, we get the start date - I am just instantiating a new Date object which defaults to right now.
Along with that, we will define a variable where we can keep track of where we are in the iteration.
Next, we need somewhere to keep track of the values over time.
Lastly, a value to hold the starting value.
let startDate = Date() // Today, now.
var iterDate = startDate
var vals: [Date: Int] = [:]
let startingValue: Int = 1
Step 3 - The Loop
Now, the fun part - the loop. This part will be documented in the code.
// Execute the loop until the end of the start date's month.
while iterDate.month == startDate.month {
// First, check if this is the first iteration -
if vals.count == 0 {
// If so, there is nothing to double, so we just set the starting value.
vals[iterDate] = startingValue
} else {
// If there are already values - get the previous days value, double it, and save.
if let val = vals[iterDate.prevDay] {
vals[iterDate] = val * 2
}
}
// Lastly, move to the next day.
iterDate = iterDate.nextDay
}
Step 4 - Final Value
Now that we have a dictionary of all of the values, as they grow, we can get the month-end value. First, sort the dictionary - then get the value. Getting the value this way means that you don't need to know the date.
let sortedVals = vals.sorted(by: { $0.0 < $1.0 })
if let monthEnd = sortedVals.last {
let monthEndVal = monthEnd.1
// Use the value, here.
}
There it is - hope that solves the problem!
Full Code
import Foundation
extension Date {
/// The month component of the provided date.
var month: Int {
return Calendar.current.component(.month, from: self)
}
/// Exactly one day before the provided date.
var prevDay: Date {
return Calendar.current.date(byAdding: .day, value: -1, to: self)!
}
/// Exactly one day after the provided date.
var nextDay: Date {
return Calendar.current.date(byAdding: .day, value: 1, to: self)!
}
}
let startDate = Date() // Today, now.
var iterDate = startDate
var vals: [Date: Int] = [:]
let startingValue: Int = 1
// Execute the loop until the end of the start date's month.
while iterDate.month == startDate.month {
// First, check if this is the first iteration -
if vals.count == 0 {
// If so, there is nothing to double, so we just set the starting value.
vals[iterDate] = startingValue
} else {
// If there are already values - get the previous days value, double it, and save.
if let val = vals[iterDate.prevDay] {
vals[iterDate] = val * 2
}
}
// Lastly, move to the next day.
iterDate = iterDate.nextDay
}
let sortedVals = vals.sorted(by: { $0.0 < $1.0 })
if let monthEnd = sortedVals.last {
let monthEndVal = monthEnd.1
// Use the value, here.
}

Compare two Dates in SAPUI5

I want to compare, whether Date A is greater than Date B. But I always get false, even if Date A is greater.
var oDatepicker = this.getView().byId("Date");
var oFormat = sap.ui.core.format.DateFormat.getInstance({ pattern: "d.M.y" });
var oDate = oFormat.format(new Date());
var oDatepickerParsed = oFormat.parse(oDatepicker.getValue());
if(oFormat.format(oDatepickerParsed) > oDate){
return true;
} else {
return false;
}
I tried to instantiate a Date-Object based on oDatepicker.getValue() to compare Date-Object with Date-Object, but there is something wrong.
var oDateObject = new Date(oDatepicker.getValue())
oDatepicker.getValue() is = '01.11.2020' type string. Whats wrong?
Did you try the DatePicker method getDateValue() which gives you "the date as JavaScript Date object. This is independent from any formatter."

How to compare two dates in C++Builder. 1 date from MaskEdit, 2 date from Date()

I have to compare two dates.
The first one I get from the TMaskEdit component with the DD-MM-YYYY mask.
I get the second date from the Date() function.
I tried something like this:
String MaskEditDate = me3->Text.Trim();
String ActualDate = Date().FormatString("DD-MM-YYYY");
TDate TDMaskEditDate = StrToDate(MaskEditDate);
TDate TDActualDate = StrToDate(ActualDate);
if (TDMaskEditDate > TDActualDate)
{
ShowMessage("TDMaskEditDate > TDActualDate");
}
if (TDMaskEditDate == TDActualDate)
{
ShowMessage("TDMaskEditDate == TDActualDate");
}
if (TDMaskEditDate < TDActualDate)
{
ShowMessage("TDMaskEditDate < TDActualDate");
}
But, when I try to convert a string to a date, I get an error message like '2000-01-01' is not a valid date and I do not know why.
StrToDate() parses the input string according to the format specified by the global ShortDateFormat and DateSeparator formatting variables in the SysUtils unit. Those variables are initialized at app startup to your OS's current user locale. This is documented behavior in BCB's help file.
So clearly, one of the input strings you pass to StrToDate() does not match the format that your OS is using for dates, which is why you get the error.
To do what you are attempting, you would have to update those formatting variables to match the format used by your input (as the overloaded version of StrToDate() that takes a TFormatSettings as input did not exist yet in BCB6). And there is absolutely no reason to take a TDate from Date(), convert it to a String, and then parse it back into a TDate, that is just redundant.
Try this instead:
String MaskEditDate = me3->Text.Trim();
TDate TDActualDate = Date();
String oldShortDateFormat = ShortDateFormat;
Char oldDateSeparator = DateSeparator;
ShortDateFormat = "DD-MM-YYYY";
DateSeparator = '-';
TDate TDMaskEditDate = StrToDate(MaskEditDate);
ShortDateFormat = oldShortDateFormat;
DateSeparator = oldDateSeparator;
However, you really should not be using a T(Mask)Edit for date input anyway. A much safer option is to use the TDateTimePicker control instead. Set its Kind property to dtkDate and then read its Date property when needed. There is no need to process your date values using strings at all:
TDate TDDateTimePickerDate = DateTimePicker1->Date;
TDate TDActualDate = Date();
if (TDDateTimePickerDate > TDActualDate)
{
ShowMessage("TDDateTimePickerDate > TDActualDate");
}
else if (TDDateTimePickerDate == TDActualDate)
{
ShowMessage("TDDateTimePickerDate == TDActualDate");
}
else //if (TDDateTimePickerDate < TDActualDate)
{
ShowMessage("TDDateTimePickerDate < TDActualDate");
}
Alternatively:
#include <DateUtils.hpp>
TDate TDDateTimePickerDate = DateTimePicker1->Date;
TDate TDActualDate = Date();
switch (CompareDate(TDDateTimePickerDate, TDActualDate))
{
case GreaterThanValue:
ShowMessage("TDDateTimePickerDate > TDActualDate");
break;
case EqualsValue:
ShowMessage("TDDateTimePickerDate == TDActualDate");
break;
case LessThanValue:
ShowMessage("TDDateTimePickerDate < TDActualDate");
break;
}

Google script not recognising date

I'm trying to write some code to check values in a spreadsheet column to see if they are valid dates. However, even if I put in a date in a cell with the format set to date, it doesn't seem to recognise it as a date. When I debug the date objects are listed as "new Date" but if I attempt to ask Logger to getDate() I receive the following error :
TypeError: Cannot find function getDate in object Sat Jun 05 2010 01:00:00 GMT+0100 (BST). (line 15, file "myCode")
I can set my objects as dates by calling 'new Date()' which means that they are recognised as dates but this changes all the objects to dates whether they should be or not.
Here is my code:
function onMyPress(){
var sheet = SpreadsheetApp.getActive().getActiveSheet()
var myRange = sheet.getRange(2,2,8,1)
var myValues = myRange.getValues()
for (i=0; i<8; i++){
var testDate = myValues[i]
if (isDate(testDate)) {sheet.getRange(i+2,3,1,1).setValue("Date")
}
else{
sheet.getRange(i+2,3,1,1).setValue("Not Date")
}
Logger.log(testDate.getDate())
}
}
function isDate(testDate) {
if (Object.prototype.toString.call(testDate) !== "[object Date]") {
return false;
}
else {
return true;
}
}
Thanks for looking.
The problem is that getValues() returns a 2D array and you script assigns a "row" (a
JavaScript array) instead of cell value (a JavaScript string, Date, etc.) to testDate on the following line
var testDate = myValues[i]
One alternative is to replace the above code line by by something like the following:
var testDate = myValues[i][0]
assuming that your dates are on the first column.
"Cannot find function getDate in object" means that you are calling getDate() on an object that is NOT a Date object.
I am guessing "testDate" is a String object? If you step through the code, does it go into the "else" clause?
You need to:
Check that your String object contains a correctly formatted date
(which seems to be the case)
Then CONVERT it to a Date object, like this: var realDate = new Date(testDate);
See working example here:
https://jsfiddle.net/uyowax8o/
// Convert to Date object
var realDate = new Date(testDate);
// This now works
alert(realDate.getDate());