Convert month and year into normal date format in reactjs - reactjs

<DatePicker onChange={this.dateSelect} value={this.state.dateselected} format={"MM/YYYY"} mode="month" picker="month" disabledDate={(current) => {
return moment().add(-4, 'month') >= current;
}} />
date picker didn't shows the value on edit.. We get date as MM/YYYY format from backend. How to display?

You can convert the date using moment when passing the value prop, as:
<DatePicker
value={moment(this.state.dateselected, "YYYY/MM")}
onChange={onChange}
format={"YYYY/MM"}
picker="month"
disabledDate={(current) => {
return moment().add(-4, "month") >= current;
}}
/>
View demo on codesandbox

You need to parse the date components and pass them into the Date() constructor.
const [month, year] = "01/2022".split("/");
const date = new Date(parseInt(year), parseInt(month) - 1);
console.log(date.toString());
// 'Sat Jan 01 2022 00:00:00 GMT-0600 (Central Standard Time)'

you can convert it via dateformat library for example:
1. npm install dateformat
2. import dateFormat from 'dateformat';
3. dateFormat("2022-03-7T08:59:00.000Z", "mmmm dS, yyyy") to get March 7th, 2022
or dateFormat("2022-03-7T08:59:00.000Z", "dddd, mmmm dS, yyyy") to get Tuesday, March 7th, 2022.
https://www.npmjs.com/package/dateformat

I think it gives an error is because new Date() function only accepts a specific format YYYY-MM-DD or YYYY/MM/DD so if your Date is not in that format then it will give you an error.
So what you can do is convert your date into a string and pass date, month, year as arguments. You can use the below code for that.
function convertFromStringToDate(responseDate) {
let dateComponents = responseDate.split('T');
let datePieces = dateComponents[0].split("-");
let timePieces = dateComponents[1].split(":");
return(new Date(datePieces[2], (datePieces[1] - 1), datePieces[0],
timePieces[0], timePieces[1], timePieces[2]))
}
convertFromStringToDate("21-03-2020T11:20:30")

Related

How to change the time format from HH:MM to 2023-01-25T19:15:27.615Z in React Js

Basically, the most scenarios of programming in react js. The conversion of time is from this 2023-01-25T19:15:27.615Z to HH:MM. So, here in my scenario I want to make the vice versa of it.
within moment you can do this by telling moment the format you are providing for instance moment('13:00', 'HH:mm'); is valid and the return object can be converted to ISO string with .toISOString()
You can use date-fns library.
Firstly install npm install date-fns
import {format} from 'date-fns'
...
format(new Date(),'HH:mm') // MM for months you have to use mm
An external library is not needed to set the hours and minutes for the current date and get an ISO string — a simple function will work:
function timeToIsoString (
hoursMinutes,
{ date = new Date(), utc = false } = {},
) {
const [h, m] = hoursMinutes.split(":").map(Number);
const d = new Date(date.getTime());
d[utc ? "setUTCHours" : "setHours"](h);
d[utc ? "setUTCMinutes" : "setMinutes"](m);
return d.toISOString();
}
const input = "12:34";
// Interpreting time in local time zone:
const output1 = timeToIsoString(input);
console.log(output1);
// Interpreting time in UTC:
const output2 = timeToIsoString(input, { utc: true });
console.log(output2);
// Starting with an existing date:
const date = new Date(Date.UTC(2008, 8, 15));
const output3 = timeToIsoString(input, { date, utc: true });
console.log(output3); // "2008-09-15T12:34:00.000Z"

How to convert 2021-07-14T00:00:00.000Z into a standard date in YYYY-MM-DD format

Can someone please explain how to convert this 2021-07-14T00:00:00.000Z date string value into the YYYY-MM-DD format in react.js (javascript)
You can simply use moment.js
install moment.js package by simply typing this in your terminal
npm install moment --save
2.Import moment file into your respective .js file
import moment from "moment";
3.You can simply use the folowing code to convert
moment("2021-07-14T00:00:00.000Z").utc().format('YYYY-MM-DD')
or
console.log(moment("2021-07-14T00:00:00.000Z").utc().format('YYYY-MM-DD'));
and the output will be
2021-07-14
You can use datefns.
import {format} from 'date-fns';
console.log(format(new Date("2021-07-14T00:00:00.000Z"), 'p, dd/MM/YYYY'));
A great blog
https://blog.stevenlevithan.com/archives/date-time-format
wanted format :
YYYY-MM-DD
using :
internal script
external script
<!DOCTYPE html>
<html>
<body>
<!--... external javascript ...-->
<script type="text/javascript" src="https://stevenlevithan.com/assets/misc/date.format.js"></script>
<h2>JavaScript new Date() - YYYY-MM-DD </h2>
<p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<script>
const d1 = new Date("2021-07-14T00:00:00.000Z")
// 01 - input
document.getElementById("demo1").innerHTML = d1;
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
// 02 - using function formatDate
var result2 = formatDate(d1);
console.log(result2);
document.getElementById("demo2").innerHTML = result2;
// 03 - external javascript
var result3 =d1.format("yyyy/mm/dd");
document.getElementById("demo3").innerHTML = result3;
</script>
</body>
</html>
OUTPUT :
Wed Jul 14 2021 02:00:00 GMT+0200 (Central European Summer Time)
2021-07-14
2021-07-14
You can use date formatting packages like dayjs, moment.js or strftime

Why I am getting this warning message, does not conform to the required format, "yyyy-MM-dd" in ReactJS?

I tried to assign a value to the Date (input). But I got the warning message and the Date field was also not getting updated with the assigned value.
Warning message: The specified value "Sun May 23 2021 16:06:23 GMT+0530 (India Standard Time)" does not conform to the required format, "yyyy-MM-dd".
How to assign a value (date) to the Date Input field in React using useState() hook?
Please let me know your suggestions. Thanks.
useState:
const todayDate = new Date();
const [ expenseDate, setExpenseDate ] = useState(todayDate);
JSX Part:
<label htmlFor="date-val">
<input type="date" name="date-val" value={expenseDate} onChange={onDateChangeHandler} required />
</label>
You need to convert your Date in specific yyyy-mm-dd format
Try this
const todayDate = new Date();
const formatDate = todayDate.getDate() < 10 ? `0${todayDate.getDate()}`:todayDate.getDate();
const formatMonth = todayDate.getMonth() < 10 ? `0${todayDate.getMonth()}`: todayDate.getMonth();
const formattedDate = [todayDate.getFullYear(), formatMonth, formatDate].join('-');
const [expenseDate, setExpenseDate] = useState(formattedDate);
The resulting value includes the year, month, and day, but not the
time
For better understanding, go through official documentation

Moment.js datepicker won't accept my dates

I'm currently working on a project using React.js.
I’m using material-ui datepicker and I'm blocking all dates except the 14 upcoming dates. What I want is that every Thursday I get 14 new dates in my datepicker.
I'm supposed to add my beginningOfWeek and endOfWeek into my maxDate and minDate, but it's currently not working and I can't figure out how to get it right.
It types out the correct answer in the log but when I press the datepicker I'm getting an error and the debugger says:
TypeError: d2.getFullYear is not a function at monthDiff
What am I doing wrong?
I've used this example for my own code. How to get the date ranges of a given week number in JS
This is my code:
var moment = require('moment');
const w = moment().weekday();
const daysToSubtract = (w + 3)%7;
const beginningOfWeek = moment(new Date()));
const endOfWeek = moment(new Date()).add(-daysToSubtract, 'days');
console.log(beginningOfWeek.format('MM/DD/YYYY h:mm a'),
endOfWeek.format('MM/DD/YYYY h:mm a'))
<div className="center-container">
<DatePicker hintText={newdate} mode="landscape" maxDate={endOfWeek}
minDate={beginningOfWeek}/>
</div>
I solved it by doing this. I changed my maxDate into maxDate = {new Date(endOfWeek)}/>
const moment = require('moment');
const w = moment().weekday();
const daysToSubtract = ((w + 3 + Math.floor(hours/16)))%7 ;
const beginningOfWeek = moment().add(-daysToSubtract, 'days');
const endOfWeek = moment().add(14-daysToSubtract, 'days');
console.log(beginningOfWeek);
console.log(endOfWeek);
<div className="center-container">
<DatePicker hintText={newdate} mode="landscape" minDate={new
Date()} maxDate = {new Date(endOfWeek)}/>
</div>

Format Date to Year

I've got a date coming in from an API that returns the date like this: 2012-10-12 00:00:00
I'm printing it to my page like this:
<span class="year" ng-bind-html="hit._highlightResult.original_release_date.value"></span>
with original_release_date.value being that date (2012-10-12 00:00:00). Does anyone know a quick and easy way to just return the year?
Any help is appreciated. Thanks in advance!
you can use the date api in angularjs
<span class="year"> {{ hit._highlightResult.original_release_date.value | date:"yyyy" }} </span>
hit._highlightResult.original_release_date.value should be a (according to doc)
Date to format either as Date object, milliseconds (string or number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is specified in the string input, the time is considered to be in the local timezone.
so create javascript date object and format it to show only the year,
step 1 - create a filter to get a date object from a string (2012-10-12 00:00:00)
app.filter('dateToISO', function() {
return function(input) {
var dateTime = input.split(" ");
var date = dateTime[0];
var datePartials = date.split("-");
var time = dateTime[1];
var timePartials = time.split(":");
var formattedDate = new Date();
formattedDate.setFullYear(datePartials[0]);
formattedDate.setMonth(datePartials[1]-1);
formattedDate.setDate(datePartials[2]);
formattedDate.setHours(timePartials[0]);
formattedDate.setMinutes(timePartials[1]);
return formattedDate;
};
});
step 2 - create a controller function to get the date object
$scope.getDate = function() {
return $filter('dateToISO')('2012-10-12 00:00:00');
};
step 3 - call that function and get the date object to format in the HTML
<span class="year"> {{ getDate() | date:"yyyy" }} </span>
here is the working Demo Plunker
This may be a bit off and cheating but I think '2012-10-12 00:00:00'.split('-')[0] will do the trick

Resources