Date Format effecting non date related search query - javascript

I feel like the answer to this is probably gonna be a pretty duh thing, but i played endlessly with trying to get the universal date picker to show the proper date in react and came up with INTL.datetime('fr-ca' etc etc) and then replace the slashes with -. Great it works on the searches involving dates. I try to do the get for no date ranges and it spits back an error and wont display the return
Here is error
react-dom.development.js:1383 The specified value "Tue Dec 01 2020 09:52:36 GMT-0800 (Pacific Standard Time)" does not conform to the required format, "yyyy-MM-dd".
Here is my code for the entire component. Should i useeffect for getDups() and just set the time value to nothing?
import React, { useState,useContext, useEffect } from "react";
import ListItem from "./ListItem";
import KeyModal from "./KeyModal";
import LeadContext from "../context/lead/leadContext";
const ListViewer = () => {
const leadContext = useContext(LeadContext);
const { leads, clearLeads, getLexs, keys, postLeads, getDups,sendTodays,getReleases } = leadContext;
const [startDate, setStartDate] = useState(new Date(Date.now()))
const [endDate, setEndDate] = useState(new Date(Date.now()))
const onChange = e =>{
setStartDate(e.target.value)
}
const onChange2 = e =>{
setEndDate(e.target.value)
}
console.log(leads)
const dates = {startDate, endDate}
return (
<div className='grid-2'>
<div>
<button className="p-2 btn btn-sm btn-danger" onClick={()=>getDups()}> Get All Dups </button>
<button className="p-2 btn btn-sm btn-success" onClick={()=>sendTodays()}>Send Todays Scrapes</button>
<button className="p-2 btn btn-sm btn-primary" onClick={()=>getReleases(dates)}>Get Range Releases</button>
<button className="btn btn-sm btn-dark" onClick={()=>getLexs(dates)}>Get Range Lexis Info</button>
</div>
<div>
<form>
<div className='grid-2'>
<div>
<label>Enter a Date Range </label>
<input
type='date'
name='startDate'
value={
startDate &&
Intl.DateTimeFormat("fr-CA", {
year: "numeric",
month: "numeric",
day: "numeric",
}).format(new Date(startDate).replace(/-/, '/').replace(/-/,'/'))
}
id='startDate'
onChange={onChange}
/>
</div>
<div>
<input
type='date'
name='endDate'
value={
startDate &&
Intl.DateTimeFormat("fr-CA", {
year: "numeric",
month: "numeric",
day: "numeric",
}).format(new Date(endDate).replace(/-/, '/').replace(/-/,'/'))
}
id='endDate'
onChange={onChange2}
/>
</div>
</div>
</form>
).format(new Date(e.target.value.replace(/-/, '/').replace(/-/,
</div>
{keys.length > 0 ? <KeyModal keys={keys}/> :''}
<br/>
<br/>
{leads.length > 0 ?
<div className='grid-2'>
<div> <button onClick={()=>clearLeads()} className='btn btn-dark btn-block'>Clear Leads</button></div>
<div> <button onClick={()=>postLeads(leads)}className='btn btn-success btn-block'>Post Leads</button></div>
</div>:''}
<div className = 'grid-2'>
<div> {leads.length > 0 ? leads.filter(function(item) {
return item["dob"] === undefined;
}).map((lead) => <ListItem key={lead.dupId} lead={lead} />)
: ""}</div>
<div>
{leads.length > 0 ?
leads.filter(function(item) {
return item["dob"] !== undefined;
}).map((lead) => <ListItem key={lead.dupId} lead={lead} />)
: ""}</div>
</div>
</div>
);
};
export default ListViewer;

The MDN docs on <input type="date"> state that:
the parsed value is always formatted yyyy-mm-dd
So you shouldn't pass a Date object in your inputs' value attribute, since a Date's default string representation is something like:
Tue Dec 01 2020 09:52:36 GMT-0800 (Pacific Standard Time)
when value should be:
2020-12-01
What appears in the <input type="date"> text box is up to the browser locale, you cannot change the way the date appears in a native date picker.
A few other pointers as well:
new Date(Date.now()) is redundant, you may use new Date() without any arguments to get a Date object pointing to the present instead.
You cannot use replace() functions on Date objects - not before turning them into Strings, you'll get an Error otherwise. You probably meant to do:
Intl.DateTimeFormat("fr-CA", {
year: "numeric",
month: "numeric",
day: "numeric",
}).format(new Date(endDate)).replaceAll('-', '/')
Speaking of replace(), you don't have to chain replace() twice to substitute all dashes (-) for slashes (/). You can use a replaceAll() like above, or type replace(/-/g, '/') (notice the "g" after the regular expression object).
Not that the above pointers solve your problem. You still have to convert your Date in a "yyyy-MM-dd" string.

Related

How to compose two different input values and printing its value compared?

Thank you for opening this question in advance.
The thing I want to make(and understood)is time input feature, that allows user to see the expected time; by comparing two (given) input value provided by user.
For example, (1) user will input any starting time to first time input section.
(2) user will input any ending time to set.
(3) By substracting ending value with starting value, it should print the outcome.
(start) 10:00
(end) 14:00
And this is goal:
End - start = 4 hours (expected time; to accomplish its task)
So far, I have attmpted searching for useState, getTime method as a clue to make the feature I described above.
But something is missing...for example:
var diffTime = (end.getTime() - start.getTime()) / (1000);
But I have no idea how to expand this idea further than this point.
How should I print the (expected time) value by comparing the input values received from two different time input values?
import React from "react";
import styled from "styled-components";
function App() {
return (
<div className="App">
<h3>Section</h3>
<div className="time">
<label for="due">Set your time to compare it</label>
<p></p>
Start
<input id="due" type="datetime-local" name="duedate" />
End
<input id="due" type="datetime-local" name="duedate" />
<p>
<label for="due">Time you spent</label>
<StylingBox>
<div className="square-box">
<div className="sqaure-content">
<p>(place to display the calculated value here)</p>
</div>
</div>
</StylingBox>
</p>
</div>
</div>
);
}
export default App;
This is a minimal setup that can help you get started:
import { useEffect, useState } from "react";
export default function App() {
// This state variable will hold the starting date:
const [start, setStart ] = useState(null);
// This state variable will hold the ending date:
const [end, setEnd ] = useState(null);
// This state variable will hold the difference between the starting and ending date:
const [ final, setFinal ] = useState(null);
// Update starting date on input change event:
function handleStartChange(e){
setStart(new Date(e.target.value).getTime());
}
// Update ending date on input change event:
function handleEndChange(e){
setEnd(new Date(e.target.value).getTime());
}
useEffect(function runWhenStartOrEndChange(){
// Calculate difference only if both starting and ending dates are present and not null
if ( end && start){
const diffTime = ((new Date(end).getTime() - new Date(start).getTime()) / (1000)) / 60;
setFinal( diffTime );
}
}, [start, end])
return (
<>
<label htmlFor="due">Set your time to compare it</label>
Start:
<input onChange={handleStartChange} id="due" type="datetime-local" name="duedate" />
End:
<input onChange={handleEndChange} id="due" type="datetime-local" name="duedate" />
<label htmlFor="due">Time you spent</label>
<div>{final} minutes</div>
</>
);
}
You can even approach this using just a single state variable, but I'll leave this up to you as a practice.
Working demo:
<script crossorigin src="https://unpkg.com/react#18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#18/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/babel-standalone#6/babel.min.js"></script>
<div id="root"></div>
<script type="text/babel">
const useEffect = React.useEffect;
const useState = React.useState;
function App() {
// This state variable will hold the starting date:
const [start, setStart ] = useState(null);
// This state variable will hold the ending date:
const [end, setEnd ] = useState(null);
// This state variable will hold the difference between the starting and ending date:
const [ final, setFinal ] = useState(null);
// Update starting date on input change event:
function handleStartChange(e){
setStart(new Date(e.target.value).getTime());
}
// Update ending date on input change event:
function handleEndChange(e){
setEnd(new Date(e.target.value).getTime());
}
useEffect(function runWhenStartOrEndChange(){
// Calculate difference only if both starting and ending dates are present and not null
if ( end && start){
const diffTime = ((new Date(end).getTime() - new Date(start).getTime()) / (1000)) / 60;
setFinal( diffTime );
}
}, [start, end])
return (
<React.Fragment>
<label htmlFor="due">Set your time to compare it</label>
<br /> Start:
<input onChange={handleStartChange} id="due" type="datetime-local" name="duedate" />
<br/> End:
<input onChange={handleEndChange} id="due" type="datetime-local" name="duedate" />
<br /><label htmlFor="due">Time you spent: {final} minutes</label>
</React.Fragment>
);
}
const el = document.querySelector("#root");
const rootEl = ReactDOM.createRoot(el);
rootEl.render(<App />);
</script>

How to change the time to the format with moment and datePicker AntD?

How to change the time to the format when the day is 23 o'clock. For example, when I click on 23 in the datapicker, 11 is shown, but i want to see 23
Code
function onChange(date, dateString) {
console.log(date, dateString);
}
ReactDOM.render(
<Space direction="vertical">
<DatePicker
allowClear
placeholder="укажите дату"
local="ISO 8601"
showTime={{
defaultValue: moment("00:00:00", "HH:mm:ss")
}}
format="YYYY-MM-DD hh:mm:ss"
onChange={onChange}
/>
</Space>,
document.getElementById("container")
);
Lowercase, i.e. 'h' or 'hh' is used for 12 hour format in momentjs.
Now since you want a 24 hour format, use 'H' or 'HH'. Use format="YYYY-MM-DD HH:mm:ss". This should work.

Java Date getHours() and display in Angular page

When I click the Create new Ticket #1,
I'm able to automatically display the current year/month/day as show here: But I need the time aswell.
Here is how I've implemeted it:
My Java Pojo:
public class Ticket implements Serializable {
#Column(name = "jhi_date")
private LocalDate date;
//getters and setters
}
My ticket-popup.service.ts
setTimeout(() => {
// populate date with current date if new
const tickets = new Ticket();
const now = new Date();
tickets.date = {
year: now.getFullYear(), // works fine
month: now.getMonth() + 1, // works fine
day: now.getDate(), // works fine
time: now.getTime(), // doesnt return anything as shown in image
hour: now.getHours() // doesnt return anything as in image
};
this.ngbModalRef = this.ticketModalRef(component, tickets);
resolve(this.ngbModalRef);
}, 0);
It's most probably caused by the ngbDatepicker component. What could be it's equivalent to replace ?
<div class="form-group">
<label class="form-control-label" for="field_date">Date</label>
<div class="input-group">
<input id="field_date" type="text" class="form-control" name="date" ngbDatepicker #dateDp="ngbDatepicker" [(ngModel)]="ticket.date"
/>
<span class="input-group-append">
<button type="button" class="btn btn-secondary" (click)="dateDp.toggle()"><i class="fa fa-calendar"></i></button>
</span>
</div>
</div>
Github sample here
Here is how I managed to get the time:
public class Ticket implements Serializable {
//#Column(name = "jhi_date")
//private LocalDate date;
#Column(name = "jhi_timestamp")
private ZonedDateTime timestamp; // used ZonedDateTime instead of LocalDate
//getters and setters
}
Used Angular Date Pipe in My ticket-popup.service.ts
setTimeout(() => {
// populate date/time with current time if new
const ticket = new Ticket();
ticket.timestamp = this.datePipe // used Pipe date format
.transform(new Date(), 'yyyy-MM-ddThh:mm');
this.ngbModalRef = this.ticketModalRef(component, ticket);
resolve(this.ngbModalRef);
}, 0);
Got rid of ngbDatepicker from
ticket-dialog.component.html
<div class="form-group">
<label class="form-control-label" for="field_timestamp">Timestamp</label>
<div class="d-flex">
<input id="field_timestamp" type="datetime-local" class="form-control" name="timestamp" [(ngModel)]="ticket.timestamp"
/>
</div>
</div>
result:

Pass the value from a datePicker (start date) to a second datePicker (end date) with React JS

I have two datePickers (StartDate & EndDate) what I want to do is after I select the StartDate pass that value to the EndDate so I can choose a date after the StartDate.
For example if I choose my StartDate to be December 10 then when I go to my EndDate datepicker I wont be able to choose any date before December 10 so that will be my starting point for the EndDate datepicker.
This is my render method.
render() {
const today = new Date();
today.setDate(today.getDate() + 1);
return (
<div className={cr.container}>
<div className ={cr.boton}>
<Divider/>
</div>
<div className={cr.rows}>
<div>
<div>
<DatePicker
hintText="Start Date"
minDate = {today}
/>
<br/>
<DatePicker
hintText="End Date"
/>
</div>
</div>
</div>
</div>
);
}
}
I'll appreciate the help on this...
Thanks in advance.
Try updating the component state after selecting the start date:
<DatePicker
selected={this.state.startDate}
onChange={this.handleChangeStart}
hintText="Start Date"
minDate={today}
/>
... And then for your end date component, try using that value fore minDate
<DatePicker
selected={this.state.endDate}
onChange={this.handleChangeEnd}
hintText="End Date"
minDate={this.state.startDate}
/>
You should be able to do something like this if you are using material-ui date picker:
<DatePicker
hintText="Start Date"
minDate = {today}
onChange={(null, date) => { setState({ startDate: date }); }}
value={this.state.startDate}
/>
<DatePicker
hintText="End Date"
defaultDate={this.state.startDate + 1}
{/* or however you calculate endDate */}
value={this.state.endDate}
onChange={(null, date) => { setState({ endDate: date }); }}
/>
See the controlled example from the docs.

how to combine values from Datepicker & Timepicker in one variable

I have angular App U I have Datepicker & Timepicker using angular-ui when user select date $Scope.dt and set time $Scope.mytime I am trying to combine in one $Scope.SelectedDateTime I get NaN. I don't know how to fix it
update
when user select date $scope.dt value will be 'ok when user select date it will 'Thu Mar 05 2015 00:00:00 GMT-0500 (Eastern Standard Time)' and $scope.mytime value 'Thu Mar 05 2015 23:30:00 GMT-0500 (Eastern Standard Time)' how to combine them in one variable
html
<h4>Popup</h4>
<div class="row">
<div class="col-md-6">
<p class="input-group">
<input type="text" class="form-control" datepicker-popup="{{format}}" ng-model="dt" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open($event)"><i class="glyphicon glyphicon-calendar"></i></button>
</span>
</p>
</div>
</div>
<timepicker ng-model="mytime" ng-change="changed()" hour-step="hstep" minute-step="mstep" show-meridian="ismeridian"></timepicker>
<button type="button" class="btn btn-sm btn-info" ng-click="SelectedDateTime()">Today</button>
javascript
$scope.today = function() {
$scope.dt = new Date();
};
$scope.today();
$Scope.mytime = new Date();
$scope.changed = function () {
$log.log('Time changed to: ' + $scope.mytime);
};
$scope.clear = function() {
$scope.mytime = null;
};
$Scope.SelectedDateTime = function()
{
var SelectedDateTime = $scope.dt +''+$scope.mytime;
}
I solved this problem using the same ng-model for Datepicker and Timepicker.
<input type="text" ng-model="myDateModel" datepicker-options="dateOptions" ... />
<uib-timepicker ng-model="myDateModel"...></uib-timepicker>
I hope it helps you too! Good luck!
You can't concatenate or try to add date objects as if they are numbers.
What you are basically trying to do is
new Date() +" "+ new Date()
Paste that line into browser console and you will see something like:
"Thu Mar 05 2015 21:54:37 GMT-0500 (Eastern Standard Time) Thu Mar 05 2015 21:54:37 GMT-0500 (Eastern Standard Time)"
You need to deal with them as Date objects and use appropriate Date prototype methods to manipulate them
Some of the methods you would need would be:
Date.prototype.getHours()
Date.prototype.setHours()
Above assumes that you are trying to actually create a new DateTime. If not it is not clear what your expected results are
Reference: MDN Date.prototype Docs

Categories

Resources