Javascript Date Validation (Range) - php

Is it possible through Jquery/Javascript that I can validate a date with the following conditions
example date : 10/10/2011
Conditions : Not in the past (accept
today onwards) Not more than 18 months
(this can be variable)
Because the ways I found out was
var e = new Date();
Alert(e.getMonth() + 2);
but this is not what I wanted

you might want to have a look at date.js
it's a great library for manipulating dates in javascript.
http://www.datejs.com/
here's the documentation:
http://code.google.com/p/datejs/wiki/APIDocumentation
it can also do the comparisons for you!
have a look at Date.compare and Date.addMonths

You can use JQuery's Datepicker, it has validation included and is pretty nice overall.

It can be done like this:
var toValidate = new Date('10/10/2011');
var months = 18;
var now = new Date();
var minDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var maxDate = new Date(now.getFullYear(), now.getMonth() + months, now.getDate());
var valid = minDate < toValidate && toValidate < maxDate;

Related

how to change date format in jquery date coming from a datatable

aData[8] is the column number which shows date in dd-mm-yyyy format.
I want to change it to yyyy-mm-dd format for validation purpose.
var dueDate = new Date(aData[8]);
console.log(aData[8]);
var dt_to = $.datepicker.formatDate('dd-mm-yy', new Date(dueDate));
var dueDatetimestamp = dt_to.getTime();
I like to use moment.js to manipulate dates.
You could do something like that with it:
moment("13-08-2014", "DD-mm-YYYY").format("YYYY-mm-DD")
Consider this:
var str = '13-02-2014';//your format dd-mm-yyyy
var newar = str.split('-');
var tempDate = newar[2] + '-' + newar[1] + '-' + newar[0];
var d = new Date(tempDate);
console.log(d);//date object
console.log(tempDate);//new format yyyy-mm-dd
DEMO
you can use date.js to achieve :
var dateAr = '2014-01-06'.split('-');
var newDate = dateAr[0] + '-' + dateAr[1] + '-' + dateAr[2];
DEMO
Personnally, I'm using jQuery.format.date(value,'date-format'). But this is a jQuery's plugin available at https://github.com/phstc/jquery-dateFormat
Very simple to use (example from Github) :
<script>
document.write($.format.date("2009-12-18 10:54:50.546", "Test: dd/MM/yyyy"));
document.write($.format.date("Wed Jan 13 10:43:41 CET 2010", "dd~MM~yyyy"));
</script>

get date with timezone javascript

I want to compare date and with date in user timezone after user's login.
I get user's timezone with php.
now How to I take current date/time in javascript of user's timezone current time.
#everyone answered:
I don't need current local system timezone or offset in seconds.
I need users current time with dynamic time I get in php.
For example:
I have 'Asia/Kolkata' or 'America/Denver' or whatever that will be dynamic by php.
Now I can save it to hidden value so that I can get it with Javascript
and than I need current date of this timezone same like Javascript gives date object.
JavaScript uses the system's time zone. You can get the offset via GetTimezoneOffset
<script>
var date=<?php echo date("Y/m/d")?>
</script>
this might help you
Try like this
<script>
var date = '<?php echo date("Y/m/d");?>';
alert(date);
</script>
deeply you can also try like this
var today = new Date();
var localoffset = -(today.getTimezoneOffset()/60);
var destoffset = -4;
var offset = destoffset-localoffset;
var d = new Date( new Date().getTime() + offset * 3600 * 1000);
alert(d);
there you can get
Try this:
// date() function
var currDate = new Date()
var n = currDate.getTimezoneOffset();
You can send UTC string
strtotime("2013-02-08 00:00:00");
After that you would have seconsd, that you can convert simple to JS Date:
var utcString = 1360263600 /*AJAX result must be here*/;
new Date(utcString*1000);
You can use Date Object of JavaScript to get user's local system..
for example you can use following:
var d = new Date();
var time = d.getTime();
alert(time);
this will alert the the number of milliseconds since midnight.
You can send this time to your server and compare the both.
For more functions and details you can visit JavaScript Date Object
I am from Taiwan and it returns "+8" for me.
Working example
JS
function timezone() {
var offset = new Date().getTimezoneOffset();
var minutes = Math.abs(offset);
var hours = Math.floor(minutes / 60);
var prefix = offset < 0 ? "+" : "-";
return prefix+hours;
}
$('#result1').html(timezone());
HTML
<div id="result"></div>
Result
+8
I would recommend to use moment.js with moment timezone.
Then you can do something like:
moment().tz("Asia/Kolkata").format();

Passing PHP variables to jQuery integer

basically I know more or less how to do it but would like to know if there is any better way?
I have the following variables in PHP
$day; $month; $year;
The ones above have values from exploding a php date string.
Below is PHP plugin function which states the date for countdown.
<script type="text/javascript">
$(function () {
var austDay = new Date();
austDay = new Date(2013, 12, 22);
$('#defaultCountdown').countdown({until: austDay});
});
</script>
I would like to pass the date day/month/year variables into that function from PHP
how can I do it, when I tried to attach to the javavariable and put that variable in place of the date part, it didnt work.
Thanks for all help
var day = <?php echo $day ?>;
var month = <?php echo $month ?>;
var year = <?php echo $year ?>;
$(function () {
var austDay = new Date();
austDay = new Date( year, month, day );
$('#defaultCountdown').countdown({until: austDay});
});
There's a couple of ways you could skin this.
Fetch the values via $.ajax with php returning the values as a jsonified array (echo json_encode($my_values))
If the page generating the html is a php page then just new Date();
Place the values into hidden form fields anywhere on the page or into data-day, data-month, data-year attributes of a relevant object on the page and fetch the values using jquery
day = $('#hiddenfield_day').val(); //put the var day into the day field of new date, etc
Hope this helps.
Change this line:
austDay = new Date(<?= $year ?>, <?= $month ?> , <?= $day ?>);
That said, keep in mind that Javascript's new Date() month param takes a number in the 0 - 11 range.

PHP strtotime() returns false for JavaScript Date string

At browser,in JS
var today = new Date()
todaySendToServer = today.toString();
I am sending todaySendToServer to server in AJAX call or as part of URL.
At server, in PHP:
$todayJsDateString1 = preg_replace('#^(\d+)/(\d+)/(\d+)\s([\d:]+)\s([a-zA-z]{0,2})$#','$3- $2-$1 $4 $5', $todayJsDateString);
$todayTimestamp = strtotime(todayJsDateString1);
The strtotime() PHP call returns false for date strings returned by some browser(like IE9)
Is there any alternate way to achieve this?
Pass the timestamp instead, so you even don't need to use strtotime in the php side.
var today = new Date();
var ts = today.getTime() / 1000;
It's just a simple typo I guess, you missed a dollar sign:
$todayJsDateString1 = preg_replace('#^(\d+)/(\d+)/(\d+)\s([\d:]+)\s([a-zA-z]{0,2})$#','$3- $2-$1 $4 $5', $todayJsDateString);
$todayTimestamp = strtotime($todayJsDateString1);
Why not send it as a timestamp all the way?
var timestamp = new Date().getTime() / 1000;
$todayTimestamp = $todayJsDateString;

>Javascript Comparing 2 dates

I have this code in comparing dates
var startDate = jQuery("#startDate_field_id").val();
var endDate = jQuery("#endDate_field_id").val();
var startDateSplit = startDate.split("-");
var endDateSplit = endDate.split("-");
var start = new Date();
var end = new Date();
start.setFullYear( startDateSplit[0], startDateSplit[1], startDateSplit[2] );
end.setFullYear( endDateSplit[0], endDateSplit[1], endDateSplit[2] );
if( end < start ) {
alert("End Date should be less than Start Date of the Event");
}
The value of #startDate_field_id is 2011-10-05
white the value of $endDate_field_id is 2011-10-04
What do you think is the reason why this isn't working.
Any help would be greatly appreciated and rewarded.
Thanks! :)
I think your first problem is that you are using the Date object incorrectly. You are passing three arguments to the setFullYear() method, which only takes a single argument, a 4 digit year.
var start = new Date();
var end = new Date();
start.setFullYear( startDateSplit[0], startDateSplit[1], startDateSplit[2] );
end.setFullYear( endDateSplit[0], endDateSplit[1], endDateSplit[2] );
You might want to try something like this:
var start = new Date(startDateSplit[0], startDateSplit[1] - 1, startDateSplit[2])
var end = new Date(endDateSplit[0], endDateSplit[1] - 1, endDateSplit[2]);
I'd use UNIX epoch timestamps for the comparison:
if (end.getTime() > start.getTime()) {
alert('...');
}
Because setFullYear method month parameter accept 0..11, means 9 is October.
why not use
var start = new Date(startDate);
var end = new Date(endDate);
var start = new Date(Number(startDateSplit[0]), Number(startDateSplit[1])-1, Number(startDateSplit[2]));
var end = new Date(Number(endDateSplit[0]), Number(endDateSplit[1])-1, Number(endDateSplit[2]));
or simply:
I am not sure I correctly understand your question .
I guess you want make sure that the end date must be greater than start date.
your code will work fine if you cahnge the if condition .And i just changed the alert message too to get proper meaning
Check this DEMO .

Categories