I am using Datepicker control https://ng-bootstrap.github.io/#/components/datepicker/overview. I am using CustomDateParserFormatter to parse the date to different format. My issue is I am using dayjs to transform the dates which intern returns the date as the javascript object which means month will returned from 0 to 11, in that case datepicker shown november in the month dropdown if I enter 12/12/2012. Is there anywhere in the datepicker I can mention that the month starts from 0 and not 1 ? right now I am adding subtracting month which doesn't look clean.
current custom parser
parse(value: string | null): NgbDateStruct | any {
const dateFormat = 'MM/DD/YYYY';
if (value) {
const otherthing = dayjs(value).format(dateFormat);
const tests = dayjs(otherthing);
const something = {
day: tests.date(),
month: tests.month() + 1,
year: tests.year(),
};
return something;
}
return null;
}
format(date: NgbDateStruct): string {
if (date) {
const something = dayjs(new Date(date.year, date.month - 1, date.day));
return something.format('MM/DD/YYYY');
}
return '';
}
Related
I'm trying to modify the below code in React Typescript. I want to return the input value in time format like - "Thu Jan 01 2022 13:03:00 GMT-0500 (Eastern Standard Time)" any suggestions how to do it?
Full Code: https://codepen.io/dcode-software/pen/jOwVqGO
function getTimeStringFromPicker(timePicker) {
const selects = getSelectsFromPicker(timePicker);
return `${selects.hour.value}:${selects.minute.value} ${selects.meridiem.value}`;
}
function numberToOption(number) {
const padded = number.toString().padStart(2, "0");
return `<option value="${padded}">${padded}</option>`;
}
activate();
You can create a new Date object and set the hours and minutes on it. From there you get convert it to a string. Like this:
function getTimeStringFromPicker(timePicker) {
const selects = getSelectsFromPicker(timePicker);
const d = new Date();
d.setMinutes(selects.minute.value);
// setHours takes in hours in 24hr format
if (selects.meridiem.value === "pm") {
d.setHours(selects.hour.value + 12);
} else {
d.setHours(selects.hour.value);
}
return d.toString();
}
If you can reach a Date object somehow, its toLocaleString() method can do something like that (the actual parameters are described here.
let date = new Date();
console.log(date.toLocaleString("en-US", {
timeZone: "EST",
dateStyle: 'full',
timeStyle: 'full',
hour12: false // this is because you seem to want a 24-hour format
}));
If you need more, moment.js might be a library to check.
I need to convert this from moment.js moment(date, 'DD MM YYYY').isBefore(moment()) to date-fns.
I tried isBefore(format(value, 'dd-MM-yyyy'), sub(new Date(), { days: 1 })). I mention that now I have to substract 1 day.
So the functionality will be to compare value which is the date given with currentDate - 1 day.
Essentially, check if future date is given, (future date includes current day).
Hope this is clear enough. My example doesn't work and I don't understand why.
Looks like you're using format instead of parse. isBefore accepts a number or Date not a string as its first argument.
See example:
function compareDate(value: string) {
return isBefore(
parse(value, 'dd-MM-yyyy', new Date()),
sub(new Date(), { days: 1 })
);
}
const test = compareDate('31-12-2020');
console.log(test);
As requested in comments
We can run the value against a function that replaces all / and \s to -.
function unifyDateString(value: string) {
try {
return value.split("/").join("-").split(" ").join("-");
} catch {
return value;
}
}
function compareDate(value: string) {
return isBefore(
parse(unifyDateString(value), "dd-MM-yyyy", new Date()),
sub(new Date(), { days: 1 })
);
}
const one = compareDate("31-12-2020");
const two = compareDate("31/12/2020");
const three = compareDate("31 12 2020");
console.log(one);
console.log(two);
console.log(three);
How can I check validation when someone try to type in field of date ex. 65.01.2020, so in this way I need something to remind user to type wrong date.
<div class="col-md-6">
Year <small>(dd.mm.gggg)</small>
#Html.TextBoxFor(model => model.year, new { #class = "form-control", maxlength = "10", minlength = "4" })
</div>
I use this script for characters:
var v = this.value;
if (v.match(/^\d{2}$.) !== null)
{
this.value = v + '.';
}
else if (v.match(/^\d{2}\/\d{2}$.) !== null)
{
this.value = v + '.';
}
Use the following regular expression to validate:
function ValidateDate(testdate)
{
var date_regex = /^(0[1-9]|1[0-2])\/(0[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/;
if (!(date_regex.test(testdate))) {
return false;
}
}
This is working for me for MM/dd/yyyy.
For DD/MM/YYYY use
var date_regex = /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d/;
# if you are considering one of js supportd formats:
ex: "yyyy-MM-DD", "MM-DD-yyyy", "MMM DD yyyy" or "DD MMM yyyy"
you can use this simple check:
const validatedDate = new Date(YOUR DATE HERE);
if (isNaN(validateDate.getTime()) {
// the date is invalid
} else {
// the date is valid
}
# if you are considering different formats:
I'd recommend using momentjs or any of the alternative libraries
ex: moment("2010 11 31", "YYYY MM DD").isValid();
if you don't want to use any library and you want to do it yourself, you'll need more than just a regex test, don't forget about checking if the year is a leap year, so if you have 29 February you can check if it's a valid date or not, also for other months you need to check if each of them has 30 or 31 days, you'll need to check all these rules manually
in this case, most probably you'll need to split your values:
ex: for const d = "25-10-2009" you can do const [day, month, year] = d.split('-')
then you'll need to check the predefined rules based on these values
I expect to get a date from my database in Ymd format.
This gives me values like 20200202. This is fine for php applications but I'm using JavaScript for the frontend.
In php, we could do something like
$date = DateTime::createFromFormat('Ymd', '20200202');
meaning I get a date object as long as the formats match.
Is there a way for JavaScript to do this?
If you are sure this date will always come in the format yyyymmdd, you can use RegEx to extract the date :
function getDate(inputDate)
{
// TODO : Check if the format is valid
const pattern = /(\d{4})(\d{2})(\d{2})/
const parts = inputDate.match(pattern);
// months start with 0 in js, that's why you need to substract 1
// -----------------------v----------v
return new Date(parts[1], parts[2] - 1, parts[3]);
}
console.log(getDate("20200202").toString());
console.log(getDate("20200213").toString());
console.log(getDate("20201231").toString());
You could always check if the format matches your requirements and then split the value you get from the database. Then you could either return a Boolean value false if not possible or a date.
const dbOutput = '20200202';
const createdDate = getDate(dbOutput);
function getDate(value) {
if(value.length !== 8) {
return false;
}
const year = +value.substring(0,4);
const month = +value.substring(4,6);
const day = +value.substring(6,8);
try {
return new Date(year, month-1, day);
} catch (error) {
return false;
}
}
I'd like to enable/disable a button based on a datepicker, and I have a setup for a check like this:
public dateChanged = false;
public availableFromDate: Date;
public availableToDate: Date;
initDatepickers() {
const currentDay = new Date();
this.availableFromDate = currentDay;
this.availableToDate = currentDay;
}
private dateCheck() {
if ((this.availableFromDate > this.availableToDate) || (this.availableFromDate === this.availableToDate)) {
this.dateChanged = false;
} else {
this.dateChanged = true;
}
console.log(this.dateChanged);
console.log(`Available from - ${this.availableFromDate}`);
console.log(`Available to - ${this.availableToDate}`);
}
The check works good upwards, and enables the button when from date is lower, however!
If you log the values to the console be button is disabled because the init value is false, not because the check works.
The two date objects are initialized differently (console.log dump):
true
clinics-upload-documents.component.ts:73 Available from - Fri Feb 22 2019 00:00:00 GMT+0100 (Central European Standard Time)
clinics-upload-documents.component.ts:74 Available to - Fri Feb 22 2019 10:52:31 GMT+0100 (Central European Standard Time)
It's never going to be false because the first date obj is # 0:00:00 however the 2nd is tied to current local time.
these are used to manipulate the dates:
onFromChange(fromDate) {
const dateType = 'from';
this.setDateValues(fromDate, dateType);
}
onToChange(toDate) {
const dateType = 'to';
this.setDateValues(toDate, dateType);
}
private setDateValues(date: Date, dateType: string) {
dateType === 'from' ? this.availableFromDate = new Date(date) : this.availableToDate = new Date(date);
this.dateCheck();
}
What am I missing so badly?
Change this:
const currentDay = new Date();
this.availableFromDate = currentDay;
this.availableToDate = currentDay;
To this:
const currentDay = new Date();
currentDay.setHours(0, 0, 0, 0);
this.availableFromDate = new Date(currentDay);
this.availableToDate = new Date(currentDay);
This will zero out the time portion and make date comparison straight forward.
Next, change this:
if (
(this.availableFromDate > this.availableToDate) ||
(this.availableFromDate === this.availableToDate)
)
To this (assuming that you want to check greater than or equal to):
if (this.availableFromDate >= this.availableToDate)
You cannot compare two dates with === although you can compare them using < <= >= >.
It looks like the Date objects that come in from your date picker via onFromChange/onToChange are pure dates (they are all at midnight), while the date objects that you create with Date() will have the current time included. The js Date class should really have been called DateTime. The mismatched times will cause the === comparison to fail.
Try using something like this to set availableFromDate and availableToDate in your initDatepickers function:
private getCurrentDate() {
const date = new Date();
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
date.setMilliseconds(0);
}
EDIT: Nevermind, the === will still fail if you do this, because Date is an object, so === checks for reference equality. Two Date objects can hold the same underlying date/time values, but they are still considered to be separate objects. Things like numbers, however, are value types, so === will tell you if the two values are equal. E.g:
5 === 5; // True, because pure numbers are value types
const number1 = { number: 5 }; // This is an object, so it is a reference type. Dates are also objects.
const number2 = { number: 5 }; // Another reference type
number1 === number2; // False, because although number1 and number2 hold the same values, they are still distinct objects.
See Salman's answer for a proper solution.