How to get the current date in React Native - date

I'm trying to get the current day/month/year in a React Native App. I am new at this, so I have many doubts about the implementation.
I tried to follow the following solution, but does not work for me:
currentDay: new Date(),
console.log('Date:'+this.state.currentDay ,);
console.log('Day: '+this.state.currentDay.getDay() , 'Month: ' + this.state.currentDay.getMonth(), 'Year :'+ this.state.currentDay.getYear());

Most easiest way to install npm install moment --save
Moment is a JavaScript date and time manipulation library for parsing, validating, manipulating, and formatting dates. 
You can simply import it in your code:
import moment from 'moment';
var now = moment().format();
if you just want current date and output in your desired format, you can use moment with format function
var currentDate = moment().format("DD/MM/YYYY");
Result
30/03/2019
You can change date format according to your requirement using Moment library
You can refer the following documents read about how to use moment and what function they will provide
https://momentjs.com
https://devhints.io/moment

Install the moment package: npm i moment
import moment from 'moment';
var dateAndTime= moment().format("DD/MM/YYYY HH:mm:ss")
output: 15/11/2019 15:33:23
var date= moment().format("DD/MM/YYYY")
output: 15/11/2019
(this output is only for current date, of course).

const onPressDateValidation = () =>{
const currentDate ='2022-02-20'
// const currentDate ='2022-02-25'
// const currentDate ='2022-02-26'
const fromDate ='2022-02-20'
const toDate = '2022-02-25'
console.log("Umesh_______1 ", currentDate);
console.log("Umesh_______2 ", fromDate);
if ( moment(currentDate).isSameOrAfter(fromDate) ) {
if( moment(currentDate).isSameOrBefore(toDate)){
alert("Show your Ad either it's Banner Ad or Video Ad")
}else{
alert(" Ad is Expired")
}
} else {
alert("Ad is not started yet")
}
}

You need to add a getDate() function after newDate() .. i.e. var date = new Date.getDate()
The following code example (which should clarify implementation purposes) is illustrated on AboutReact.com, where you can run the code online.
import React, { Component } from 'react';
import { StyleSheet, View, Alert, Text } from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
//default value of the date time
date: '',
};
}
componentDidMount() {
var that = this;
var date = new Date().getDate(); //Current Date
var month = new Date().getMonth() + 1; //Current Month
var year = new Date().getFullYear(); //Current Year
var hours = new Date().getHours(); //Current Hours
var min = new Date().getMinutes(); //Current Minutes
var sec = new Date().getSeconds(); //Current Seconds
that.setState({
//Setting the value of the date time
date:
date + '/' + month + '/' + year + ' ' + hours + ':' + min + ':' + sec,
});
}
render() {
return (
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text
style={{
fontSize: 20,
}}>
Current Date Time
</Text>
<Text
style={{
fontSize: 20,
marginTop: 16,
}}>
{this.state.date}
</Text>
</View>
);
}
}
Obviously, the style is flexible and you could omit the time element of the code sample (but it may be useful to other users)..
Hope this helps

Related

Kendo UI Calendar - clears past dates when calendar icon clicked

In my screen the Kendo UI Calendar used behaves odd.
When i come on to editing the screen and click on Calendar field if the date is past date (disabled on calendar) then the existing date value gets cleared, even though i am not making any change.
How can i persist the date value for the past dates that are disabled in the calendar.
It would be helpful to give sample code for the fix.
The same we tried with HTML calendar and JQuery Calendar and the behavior is same as of Kendo UI Calendar.
The code used is in javascript
$('#txtWFITaskStartDate').change(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
var labelName = $(this).data('validatelabel');
var CurrentId = $(this).attr('id');
var startDate = $("#" + CurrentId).val();
var duration = $('#txtWFITaskDuration').val();
if ($('#' + CurrentId).val() === "") {
varErrorClassName = 'errmsgStartDate';
DisableTaskEditControls();
$('#StartDate').after('<span class="text-danger ' + varErrorClassName + '">' + Web_IsRequired.replace("{0}", labelName) + '</span>');
}
else {
$('.errmsgStartDate').remove();
$('.errmsgEndDate').remove();
EnableTaskEditControls();
var endDate = CalculateEndDate(duration, startDate);
$('#txtWFITaskEndDate').val(endDate);
$('#EndDate').datepicker('setDate', new Date(endDate));
endDate = $('#txtWFITaskEndDate').val();
if (endDate !== "") {
EnableTaskEditControls();
} else {
varErrorClassName = 'errmsgEndDate';
$('#EndDate').after('<span class="text-danger ' + varErrorClassName + '">' + Web_IsRequired.replace("{0}", "End date") + '</span>');
DisableTaskEditControls();
}
}
});
Below is the screenshot of the dates displayed on modal popup view (MVC)
As the Start Date is past date the control displays in disabled mode. When focus to the Start Date control and focus out from it. The past date gets cleared. I want to hold the existing value, until user changes the date else the same value has to persist in the Start date text box.

How to test a datepicker with protractor?

I have been trying to make my protractor test on a datepicker work.
I have the following in my html file
<div fxFlex>
<mat-datepicker #pickerBirthdate></mat-datepicker>
<input matInput
style="visibility: hidden;"
[min]="minBirthdate"
[max]="maxBirthdate"
[matDatepicker]="pickerBirthdate"
placeholder="Fecha de nacimiento"
[(ngModel)]="registry.data.fechaNac"
name="fechaNac">
</div>
And the following on my spec file
expect(page.getElementByClass('.date-select-picker'));
// get today's date
let today: any = new Date();
let dd: any = today.getDate();
let mm: any = today.getMonth() + 1; // January is 0!
const yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if ( mm < 10) {
mm = '0' + mm;
}
today = mm + '/' + dd + '/' + yyyy;
page.sleep();
page.getElementByClass('.date-select-picker').sendKeys(today);`
The problem is, it doesn't show up any date it just looks raised.
I've read this threads but I haven't been able to make it work, I don't know if it's due to my angular version.
How to test a Angular js date picker from Protractor
https://github.com/angular/material/issues/10404
Thanks in advance and good day
I had a similar problem with the datepicker, this is how I select a date in the future:
/// click the datepicker
element(by.css('.mat-datepicker-toggle')).click();
/// opens the table with years
element(by.css('.mat-calendar-arrow')).click();
/// select year, month and day
element(by.cssContainingText(".mat-calendar-body-cell-content", "2040")).click();
element(by.cssContainingText(".mat-calendar-body-cell-content", "DEC.")).click();
element(by.cssContainingText(".mat-calendar-body-cell-content", "31")).click();
use the harness:
const harnessLoader = ProtractorHarnessEnvironment.loader();
const matDatepickerToggleHarness = await harnessLoader.getHarness<MatDatepickerToggleHarness>(
MatDatepickerToggleHarness.with({selector: 'mat-datepicker-toggle'})
);
await matDatepickerToggleHarness.openCalendar();

Material UI date picker Date format React

I can't see to format the Material UI Date picker in a React app??
When a user selects a date, I want it to format to be MM/DD/YYYY. I looked up a couple answers but it's not clear where the function to change the format is supposed to go??? For some reason, there is no clear function/location of where it goes online>>
DatePicker component
import React from 'react';
import DatePicker from 'material-ui/DatePicker';
/**
* `DatePicker` can be implemented as a controlled input,
* where `value` is handled by state in the parent component.
*/
export default class DateSelect extends React.Component {
constructor(props) {
super(props);
this.state = {
controlledDate: null,
openSnackbar: false,
snackbarText: {
dateconf: 'Date has been entered!'
}
};
}
formatDate(date){
return (date.getMonth() + 1) + "/" + date.getFullYear() + "/" + date.getDate();
}
handleChange = (event, date) => {
console.log('we are in a handle change in date select', event, date)
this.setState({
controlledDate: date,
});
// this.setState({
// openSnackbar: true
// })
};
render() {
console.log('state and props in date select', this.state, this.props)
return (
<DatePicker formatDate={this.formatDate}
hintText="Date of purchase"
hintStyle={{color:'whitesmoke'}}
inputStyle={{ color:'whitesmoke'}}
value={this.state.controlledDate}
onChange={this.props.onChange}
/>
);
}
}
///THE PARENT COMPONENT
handleDatePicker = (name, date) => {
console.log('handling date change', name, date)
this.setState(prevState => ({
currentRow: {
...prevState.currentRow,
purchase_date: date
},
purchase_date: date,
actionType: 'date'
}))
this.setState({
openSnackbar: true
})
}
<DateSelect
hintText="Purchase date"
value = {this.state.purchase_date}
onChange={this.handleDatePicker}
/>
You need to use formatDate function to format the date and time in date picker
formatDate --> This function is called to format the date displayed in the input field, and should return a string. By default
if no locale and DateTimeFormat is provided date objects are formatted
to ISO 8601 YYYY-MM-DD.
<DatePicker
hintText="Date of purchase"
hintStyle={{color:'whitesmoke'}}
inputStyle={{ color:'whitesmoke'}}
value={this.state.controlledDate}
onChange={this.props.onChange}
formatDate={(date) => moment(new Date()).format('MM-DD-YYYY')}
/>
if you do not pass any format on the date it seems that the min and max date are not working.
For more details material-ui/DatePicker
Straight from the documentation of DatePicker. Try this
<DatePicker
inputFormat="MM/dd/yyyy"
hintText="Date of purchase"
hintStyle={{color:'whitesmoke'}}
inputStyle={{ color:'whitesmoke'}}
value={this.state.controlledDate}
onChange={this.props.onChange}
/>
inputFormat should usually do the trick. You can change it around the way you want and it can be used for dateTimePicker as well.
For example,
inputFormat="yyyy/MM/dd"
or any other way
formatDate did not work for me in V4. documention suggest inputFormat and worked properly.I found usage example here
<DatePicker
openTo="year"
views={["year", "month", "day"]}
value={toDate}
onChange={(newValue) => {setToDate(newValue);}}
maxDate={maxdate}
minDate={minDate}
format="DD-MM-YYYY"
/>

How To Disable Specific Days and Dates Using BeforeShowDay In jQueryUiDatepicker?

I already have functioning code in jQueryUiDatepicker that disables Fridays and Saturdays and all previous days (plus 2 days). My issue is trying to add 2 specific dates to this existing Datepicker code that will also disable these dates.
This is my existing code on starting line 92 in jQueryUiDatepicker:
beforeShowDay: function(date) {
var show = true;
if(date.getDay()==5||date.getDay()==6) show=false
return [show];
},
beforeShow: function(){
var dateTime = new Date();
var hour = dateTime.getHours();
//If Hour is greater or equals to 8AM
if(hour >= 08){
//Disable all past days including tomorrow and today
$(this).datepicker( "option", "minDate", "+2" );
}
},
I am trying to disable 18th and 19th October 2017 and failing, this is the code I have added directly underneath the above code:
beforeShowDay: var array = ['18/10/2017', '19/10/2017']
$('input').datepicker({
beforeShowDay: function(date){
var string = jQuery.datepicker.formatDate('dd/mm/yy', date);
return [ array.indexOf(string) == -1 ]
},
My question is how can I disable all previous dates, all Fridays and Saturdays and these 2 dates in the October?
Note# This coding has to be done in jquery.ui.datepicker, not a script in html
Hope this helps
use inArray instead of indexOf and you can also disable all previous dates using minDate
var array = ["18/10/2017", "19/10/2017"];
$(function() {
$('input').datepicker({
minDate: new Date(),
beforeShowDay: function (date) {
$thisDate = date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
var day = date.getDay();
if ($.inArray($thisDate, array) == -1&&day!=5&&day!=6) {
return [true, ""];
} else {
return [false, "", "Unavailable"];
}
}
});
});
DEMO

ALLOYUI Datepicker setter and getter method

I have two input text box startdate and enddate
<input type="text" id="startdate"/>
<input type="text" id="enddate"/>
I need two simple things
On click of startdate and selection of start date, need to update
end date with +7 days.
Format needed is mm/dd/yyyy
So if any one click startdate with 01/01/2015 i.e 1st January 2015 , than end date should automatically set with 01/08/2015
On selection of startdate, I need to get enddate open automatically.
The datepicker Library I had used is ALLOYUI datepicker version 3.0
http://alloyui.com/examples/datepicker/
Can anyone please write down code please.
Guys
<script>
var datefrom;
YUI().use(
'aui-datepicker',
function(Y) {
datefrom = new Y.DatePicker(
{
trigger: '#dpfrom',
popover: {
zIndex: 1
},
calendar: {
//maximumDate : new Date(today.getFullYear(),today.getMonth()+1,today.getDate()),
minimumDate : new Date(),
},
on: {
selectionChange: function(event) {
}
}
}
);
}
);
//console.log(james);
</script>
I found the may to set minimum and maximum date but still i donot have the way to set end date +7 days to current date.
Please find similar and working one for me. Please customize it if you need anything.
<input class="form-control" type="text" id="selecteddate" placeholder="Day, Mon dd, yyyy"></input>
YUI().use(
'aui-datepicker',
function(Y) {
var datepicker = new Y.DatePicker(
{
trigger: 'input',
popover: {
zIndex: 1
},
after: {
selectionChange: function(event) {
event.preventDefault();
Y.log(datepicker.getSelectedDates());
var myDate=Y.DataType.Date.addDays(new Date(datepicker.getSelectedDates()),+6);
if (myDate.isValid()) {
$("#selecteddate").val(myDate);
}
}
}
}
);
}
);
Date.prototype.isValid = function () {
// An invalid date object returns NaN for getTime() and NaN is the only
// object not strictly equal to itself.
return this.getTime() === this.getTime();
};