Format Angular Date for DB storage - javascript

Thank you in advance
Q.1
I would like to format the Angular-UI Bootstrap date and time pickers. Every time I change the time or date the output is in the following manner Today is: "2015-03-19T22:00:00.000Z". Obviously this is in correct. And my Node-Mysql is filled with this date formatting
What's more bizzar is that There is 1 day subtracted in the date, On the time it subtracts 2 hours. My Time zone is GMT+2 See MyBin.
When I click on the date again to change it I want the date to stay as 2015-03-20 and the time to 11:20
Q.2
How can I properly validate the following
<form name="BookingForm" ng-repeat="adult in myAdults">
<h4>Adults</h4>
<p>
<input required
ng-required="true"
name="adultName"
ng-model="adultItem.name"
type="text"
class="form-control"
ng-minlength = 3
placeholder="Name">
<div class="error" ng-show="BookingForm.adultName.$dirty && BookingForm.adultName.$invalid">
<small class="error btn-danger"
ng-show="BookingForm.adultName.$error.required">
Your name is required.
</small>
<small class="error btn-danger"
ng-show="BookingForm.adultName.$error.minlength">
Your name is required to be at least 3 characters
</small>
</div>
</p>
</form>
My js Looks like this
$scope.adults = 4;
$scope.children = 2;
$scope.myAdults = [];
for (i = 0; i < $scope.adults; i ++) {
$scope.myAdults.push({});
}
If I have just one form it works fine. But if I have more than one The validation messages only show up on the last one.
Most Important is Q1
Thank you again.

datepicker is using angularjs date filter and it's localised but returned values are in GMT so 2015-03-19T22:00:00.000Z is correct for 2015-03-12T00:00:00.000Z as it will subtract 2 hours from midnight back which changes date as well, if you need a specific format you can do it with date filter as per plunker so
{{'2015-03-19T22:00:00.000Z' | date:'dd-MMMM-yyyy'}} in your timezone shall return 20-March-2015
http://angular-ui.github.io/bootstrap/#/datepicker
http://plnkr.co/edit/CoIS2BFK5O5EAaTu4Vc2?p=preview
javascript
$scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
$scope.format = $scope.formats[0];

Related

Broken Delivery Estimate Calculator

I'm hoping someone can help me figure out how to code an app that allows you to select a mailing date with jquery datepicker, select Standard or First-class shipping from a dropdown, and calculate an estimated delivery date window (7-12 Days for Standard, 3-5 Days for First-class).
I had it working when the "Mailing in" [number] "Days" accepted a string input but then it broke when I added code for the datepicker.
I also need to keep weekends & holidays excluded from the shipping calculation.
Here's a link to the full pen: https://codepen.io/allyjfuller/pen/oNXvwJL
$('#calculateShippingEstimate').click(function( event ) {
//Prevent button from 'submitting' and reloading the page
event.preventDefault();
//Capture the mailing date
var $mailingDate = $("#mailingDate").val();
var $postageType = $("#postageType").val();
var $shipStateShippingDuration = eval('data.shipTimes.' + $postageType);
var $totalShippingTime = parseInt($mailingDate) + parseInt($shipStateShippingDuration);
//Create the date
var date = new Date();
var month = date.getMonth()+1;
var day = date.getDate() + parseInt($totalShippingTime);
var year = date.getFullYear();
<form>
<section>
<label>Mailing on</label>
<input id="mailingDate" placeholder="number"></input>
</section>
<section>
<label>Postage:</label>
<select id="postageType">
<option value="Standard">Standard</option>
<option value="FirstClass">First-Class</option>
</select>
</section>
<input class="button" id="calculateShippingEstimate" type="submit" value="Get Estimated Delivery Date"></input>
<div class="results"></div>
</form>
Looking through your code snippet it seems like you're trying to hand roll a lot of features that already exist within the JS Date framework.
Once you get the starting date and the number of days for shipping, you can add those days together to create a final shipping date. From there and within a loop, you may go day by day and check whether the current date index is a weekday or not (using Date.getDay()).
With that you may check for Saturday [6] and Sunday [0] and then add days needed on top of the final date.
I've included my version of the code below with some console debugging but have not added code holidays. Holidays may be checked for using an array or map. Get all the holiday dates for a year and then have the current index check the holiday array/map to see if there are any matches. If there are, add another day to the final date.
The function for addDays is pulled from here. It adds some explanation which I think you'll find helpful.
function addDays(date, days) {
const copy = new Date(Number(date))
copy.setDate(date.getDate() + days)
return copy
}
// FINAL SHIPPING ESTIMATE
$('#calculateShippingEstimate').click(function( event ) {
event.preventDefault();
let mailingDateVal = $("#mailingDate").val();
let shippingDuration = data.shipTimes[$("#postageType").val()];
let mailingDate = new Date(mailingDateVal);
console.log("final Date: " + addDays(mailingDate, shippingDuration));
let finalDate = addDays(mailingDate, shippingDuration)
let mailingDateIndex = new Date(mailingDate);
while(mailingDateIndex <= finalDate) {
console.log("current mailDateIndex: " + mailingDateIndex)
if (mailingDateIndex === finalDate) {
break;
}
// Weekend
console.log(mailingDateIndex.getDay());
if (mailingDateIndex.getDay() == 0 || mailingDateIndex.getDay() == 6) {
console.log("weekend day hit! Adding day to final...")
finalDate = addDays(finalDate, 1);
}
mailingDateIndex = addDays(mailingDateIndex, 1);
}
});

Show the date always without seconds is not working

I have a page to edit the administrators of a post. I have some radio buttons in this page, each radio button corresponds to an administrator. When an administratotr is selected the details of that administrator appears on the form fields below the radio buttons.
One form field is a date. Im using cabon to show in this edit post administrators page the date in this format "format('d F Y - H:i')":
<div class="input-group date" data-provide="datepicker">
<input type='text' name="date" value="{{ $admin->date->format('d F Y - H:i') }}"
class="form-control" placeholder="DD/MM/YYY" />
<span class="input-group-addon"><i class="fa fa-calendar text-primary" aria-hidden="true"></i></span>
</div>
And it works fine. The date appears on this format: "07 February 2018 - 6:30".
But then I have some jQuery that receives an array with the administrators of the post from the controller and populate the details of each administrator in the form when the corresponding radio button is selected.
With this jQuery when this edit administrators page is acessed the date appears on this same format ""07 February 2018 - 6:30". But then if some amdinistrator is selected through the radio button the date field of that administrator appears with seconds: ""07 February 2018 - 6:30:00". But I dont want to show the seconds. I want this format ""07 February 2018 - 6:30".
Do you know how to do this?
jQuery:
$(document).ready(function () {
var admins= {!! $admin!!}
$("input[name='radiobutton']").click(function() {
let id = $(this).attr("id");
let data = admins.find(e => e.id == id) || {
name: "",
date: "",
};
//alert(data.date); // 2018-02-07 6:30:00
$("input[name='name']").val(data.name);
...
$("input[name='date']").val(data.date);
});
});
I don't know what went wrong along the line but from the Javascript end, moment can come to your rescue:
So, an example will be:
moment(data.date).format('DD MMMM YYYY h:mm')
PS: You have to include moment from cdn or install it via npm

How to change the angular-material datepicker current date color

I want to change the color of the current date in angular-material if that day is disabled since I have made a function that disables 2 days from now.
Example if today is 8-24-16 the datepicker disables 8-24-16 (today) and 8-25-16 (tomorrow), so I want to change the color that displays the current date if the date is disabled. Because when the current date disabled it shows the current date 8-24-16 (today) in a very light blue that is hard to see so I want to change that color to a different color that highlights more.
I tried looking at the css of angular-material but I couldn't find anything related to the css color of a disabled current date or a normal not disabled current date. I don't mind changing the color of both the normal current date and the disable current date. Also, my function that disabled the days sets the date from to days from now I don't know if this affects something.
Here is my code
<div class="form-group">
<label>Delivery Date:</label>
<md-datepicker ng-model="myDate" md-placeholder="Enter date"
md-max-date="maxDate"
md-min-date="minDate"
md-date-filter="disabledWeekends"
ng-disabled="disabled">
</md-datepicker>
</div>
My Controller
//adding two days
$scope.maxDate = new Date(
$scope.myDate.getFullYear(),
$scope.myDate.getMonth(),
$scope.myDate.getDate() + 2);
$scope.minDate = new Date(
$scope.myDate.getFullYear(),
$scope.myDate.getMonth(),
$scope.myDate.getDate() + 2);
$scope.myDate = $scope.minDate;
$scope.disabledWeekends = function (date) {
var day = date.getDay();
return day === 1 || day === 2 || day === 3
|| day === 4 || day === 5;
};
You can add new class for disable date's html tags eg: class="disableDates" and define color for this class in your css file.

Check if date in field is more than x

I would like to have a function that checks if a date in a field is more than 50 years in the past from todays date. If the date is more than 50 years in the past, a message should be shown, but there should not be any minimum date (maximum years).
I have a form where it is possible to add more fields dynamically (name + birthdate), and every new "form" should show this message under the birthday field if it is more than 50 years in the past.
The warning message under each birthdate field should be something like this (if over 50):
<div class="alert alert-warning">This person is over 50 year. Remember to do...</div>
My html setup:
<label for="id_nested-0-name">Name</label>
<input id="id_nested-0-name" maxlength="200" name="nested-0-name" type="text" />
<label for="id_nested-0-birthdate">Birthdate</label>
<input class="dateinput" datadatepicker="datepicker" id="id_nested-0-birthdate" name="nested-0-birthdate" type="date" />
<!-- If nested-0-birthdate is over 50, add html with warning message -->
<!-- New person -->
<label for="id_nested-1-name">Name</label>
<input id="id_nested-1-name" maxlength="200" name="nested-1-name" type="text" />
<label for="id_nested-1-birthdate">Birthdate</label>
<input class="dateinput" datadatepicker="datepicker" id="id_nested-1-birthdate" name="nested-1-birthdate" type="date" />
<!-- If nested-1-birthdate is over 50, add html with warning message -->
Edit:
This code works great in chrome, but does not work in safari. Anyone see what could be wrong?
<script type="text/javascript">
$(document).ready(function() {
$(function(){
$("#collapse1 input.dateinput").on("change.dp change keyup paste click propertychange",function (e){
var timediff1 = moment().diff(moment($(this).val()), 'years');
if (timediff1 >= 50 ) {
$('#alert1').remove();
$('#collapse1 .panel-body').append('<div id="alert1">Over 50!</div>');
} else {
$('#alert1').remove();
}
});
});
});
</script>
Using http://eonasdan.github.io/bootstrap-datetimepicker/ for my date picker.
Edit 2:
I was missing data-format="DD/MM/YYYY" on my input. Now everything works!
If you dont mind using moment.js
JSFiddle with demo
boolean isOldGeezer = moment().diff(moment($(this).val()), 'years') > 50;
Three part answer to this question
First you need to get the date 50 years ago. I am using a small hack here. You can find better techniques in StackOverflow.
ago50y = new Date();
ago50y.setFullYear(ago50y.getUTCFullYear()-50);
Second, compare that date when the input changes. The following code uses jQuery.
$('input.dateinput').change(function (event) {
if ($(event.target).val() < ago50y.toJSON().slice(0,10)) {
$('#alert').text('This person is over 50 year. Remember to do...');
} else {
$('#alert').text('');
}
});
Third, invoke the second part whenever you add a new set of inputs. Put the above code in a function and include that in the callback while adding the new set.
http://jsfiddle.net/FA4hJ/

Javascript Date Time Validation - yyyy-mm-dd hh:mm

I want to create a very simple javascript form validation. I have two input boxes that are populated by a datetime picker. the datetime picker populates the input box with in the format 2011-12-21 09:58. I have an input box for collection date and arrival date.
I want to validate that the 'deliverdatetime' entered is greater than the 'collectdatetime'.
The output of a failed validation should just be in a popup window saying 'deliverdate' before 'coolectdate'.
Can this be done with javascript and if so can someone give me a brief example?
my basic html form code is:
...
<td>
<input type="text" id="collectdatetime" name="collectdatetime">
</td>
<td>
<input type="text" id="deliverdatetime" name="deliverdatetime" >
</td>
...
Thanks in advance for the assistance and happy holidays to everyone.
Regards,
Ryan Smith
GIven the ISO8601 format of the date/time string, you can just compare the values as strings. It's one of the beauties of using an ISO8601 format. You have asked for the delivery time to be after the collection time, which seems backwards to me but anyhow…
<form onsubmit="return checkDates(this)">
<table>
<tr>
<td>
<input type="text" id="collectdatetime" name="collectdatetime">
<td>
<input type="text" id="deliverdatetime" name="deliverdatetime">
<td>
<input type="submit">
</table>
</form>
<script>
function checkDates(form) {
if (form.collectdatetime.value >= form.deliverdatetime.value) {
alert('Collection time must be after deliver time');
return false;
}
}
</script>
You could do something like this:
var collectTime = (new Date(document.getElementById("collectdatetime").value)).getTime(),
deliverTime = (new Date(document.getElementById("deliverdatetime").value)).getTime();
if(deliverTime > collectTime) {
//Ok!
}
This creates 2 Date objects, passing the selected values to the constructor, and then compares the times. The getTime method returns a number representing the time that has passed since 1 January 1970 00:00:00 in milliseconds.
Here's a working example.
You can create Date object from this values and compare them:
var collect = new Date($('#collectdatetime').val());
var delivery = new Date($('#deliverdatetime').val());
if (delivery < collect) {
alert('Delivery date before collect!');
}

Categories

Resources