im using bootstrap-datetimepicker from http://tarruda.github.io/bootstrap-datetimepicker/
this gives the option to select the datetime in local time, what i cannot understand is how do i convert it to UTC before sending it to the cgi. I need to do this because my server is set at GMT timezone and the input can come in from any timezone.
so i would like the user to select the time in his tz but convert that selection to gmt which sending it to my cgi script.
if there is any other better way of solving this issue also i would appreciate it.
<script type="text/javascript">
$('#timetime').datetimepicker({
maskInput: true,
format: 'yyyy-MM-dd hh:mm',
});
</script>
it is being called in the form in the below code
<label for="sdate" class="control-label">* Scheduled Date (UTC/GMT)</label>
<div id="timetime" class="controls">
<input id="sdate" name="sdate" type="text" placeholder="YYYY-MM-DD HH:MM"></input>
<span class="add-on">
<i data-time-icon="icon-time" data-date-icon="icon-calendar"></i>
</span>
</div>
final answer based on the help given by filmor
<script type="text/javascript">
$('#timetime').datetimepicker({
maskInput: true,
format: 'yyyy-MM-dd hh:mm',
});
$("form").submit(function(){
// Let's find the input to check
var $input = $(this).find("input[name=sdate]");
if ($input.val()) {
// Value is falsey (i.e. null), lets set a new one, i have inversed this, input should be truthy
//$input.val() = $input.val().toISOString();
var d = $input.val();
var iso = new Date(d).toISOString();
// alert(iso);
$input.val(iso);
}
});
</script>
further update to work on both firefox and chrome
<script type="text/javascript">
$("form").submit(function(){
// Let's find the input to check
var input = $(this).find("input[name=sdate]");
if (input.val()) {
var picker = $('#timetime').data('datetimepicker');
// alert(input.val());
// alert(picker.getLocalDate().toISOString());
input.val(picker.getLocalDate().toISOString());
}
});
</script>
Just use momentjs.
http://momentjs.com/
function getUTCDate() {
return moment($('#sdate').val()).utc().format('YYYY-MM-DDTHH:mm:ssZZ');
}
<script type="text/javascript">
$('#timetime').datetimepicker({
maskInput: true,
format: 'yyyy-MM-dd hh:mm',
});
$("form").submit(function(){
var input = $('#sdate').val();
var input = convertToUtc(input);
});
function convertToUtc(str) {
var date = new Date(str);
var year = date.getUTCFullYear();
var month = date.getUTCMonth()+1;
var dd = dategetUTCDate();
var hh = date.getUTCHours();
var mi = date.getUTCMinutes();
var sec = date.getUTCSeconds();
// 2010-11-12T13:14:15Z
theDate = year + "-" + (month [1] ? month : "0" + month [0]) + "-" +
(dd[1] ? dd : "0" + dd[0]);
theTime = (hh[1] ? hh : "0" + hh[0]) + ":" + (mi[1] ? mi : "0" + mi[0]);
return [ theDate, theTime ].join("T");
}
</script>
I'm facing the same issue, my datepicker convert 14/07/2015 00:00 GMT(PARIS) to 13/07/2015 22:00 UTC.
I use this for a workaround as i only want to use the date and not time.
var dt = new Date($scope.END_DATE.value);
dt.setUTCHours(1); //set to utc 1 a.m.
$scope.holidays.END_DATE= dt;
The date is stored as 14/07/2015 01:00 in database.
Hope it helps
This is the conversion between utc to IST an vice versa
https://jsfiddle.net/wmhmgrjs/6/
//2016-08-02 12:55:19.743-- UTC <==> 2016-08-02 6:25:19.743 PM --IST
var date = new Date('8/02/2016 12:55:48 AM UTC'); //2016-07-29 07:02:40.323
var s=date.toString();
alert(s);
var d = new Date('8/02/2016 6:25:00 PM GMT+0530');
//var d = new Date("August 2, 2016 18:26:00");
var n = d.toUTCString();
alert(n);
Related
I'm using Full Calendar, I have a starting date and I need the calendar starts the week that corresponds to this date , I need to hide the previous weeks. here is a picture that explains my question.
in this example the starting date is April 20th.
$(".fc-day").each(function() {
var startDate = $('#start_date').val();
if (($(this).data('date')) < startDate){
$(this).parents().addClass('hidden');
}
});
I found a solution how to remove previous weeks, but I don't know how to replace them with future weeks.
This is the new script :
$(".fc-day").each(function() {
startDate = $('#start_date').val();
var date1 = new Date ($(this).data('date'));
var date2 = new Date (startDate);
var DD = date2.getDate();
var MM = date2.getMonth() + 1;
var YYYY = date2.getFullYear();
var startTraining = YYYY + '-'+ MM + '-'+ DD;
if ((date1 < date2) && (($(this).parent().get(0)) !== ($('.fc-day[data-date="' + startTraining + '"]').parent().get(0)))){
$(this).closest('.fc-row').addClass('hidden');
}
});
Fullcalendar automatically renders the week the date is in according to the firstDay property, so besides settings the correct day you also have to set the firstDay property to the correct day number by calling getDay().
element.fullCalendar({
defaultDate: startDate,
firstDay: startDate.getDay()
});
I have a code and just last year, it was still working. What it does is that it disables user to pick future dates. Now that it's January, it doesn't seem to be working. I do not understand why. Please help me fix this. Your help will be appreciated.
This is the input:
<input id="reqDate" class="form-control col-md-7 col-xs-12" name="reqDate" required="required" type="date">
Javascript:
<script type="text/javascript">
var input = document.getElementById("reqDate");
var today = new Date();
var day = today.getDate();
// Set month to string to add leading 0
var mon = new String(today.getMonth()+1); //January is 0!
var yr = today.getFullYear();
if(mon.length < 2) { mon = "0" + mon; }
var date = new String( yr + '-' + mon + '-' + day );
input.disabled = false;
input.setAttribute('max', date);
</script>
By the way, I am using this code in a .php file.
Like you have used, the native input[type="date"] element supports a maximum date value:
Enter a date before 1980-01-01:
<input type="date" name="bday" max="1979-12-31">
http://www.w3schools.com/tags/att_input_max.asp
The JavaScript you are using to set the date does not zero-pad the day, so for the first of January, you would get the date max="2016-01-1". To keep with your JavaScript version, sero pad the date with:
<script>
var input = document.getElementById("reqDate");
var today = new Date();
var day = today.getDate();
// Set month to string to add leading 0
var mon = new String(today.getMonth()+1); //January is 0!
var yr = today.getFullYear();
if(mon.length < 2) { mon = "0" + mon; }
if(day.length < 2) { dayn = "0" + day; }
var date = new String( yr + '-' + mon + '-' + day );
input.disabled = false;
input.setAttribute('max', date);
</script>
With this being a PHP script, to simplify your code you could use:
<input type="date" name="bday" max="<?=date('Y-m-d')?>">
N.B. Support for input[type="date"] varies between browsers (see http://caniuse.com/#feat=input-datetime).
You can confirm the max value used is in the correct supported RCF3339 format by inspecting the element in the browser inspector.
Did you try using min attribute in the input. In html5 we can specify min or max attributres in proper date format YYYY-MM-DD
I have another question on SO Unable to read date cell. This question is related to last question but more generic. How to convert Raw date, which represents number of days since 1st Jan 1900, to a javascript date type? [ Forget office365 ].
I have number of days elapsed since 1st Jan 1900. How can I get the date from it. For ex: I need a date after 42216 days, since 1st Jan 1900, How can I calculate that date? Answer is : 31-Jul-2015.
Try this:
(function(){
var date = new Date(1900,1,1);
var dayCount = 42216;
date.setDate(date.getDate() + dayCount)
console.log(date);
})()
Try this:
start = "01/01/1900"
newDate = start.split("/");
x = new Date(newDate[2]+"/"+newDate[1]+"/"+newDate[0]);
var numberOfDaysToAdd = 42216;
x.setDate(x.getDate() + parseInt(numberOfDaysToAdd));
var dd = x.getDate();
var mm = x.getMonth() + 1;
var yyyy = x.getFullYear();
var format = dd+'/'+mm+'/'+yyyy;
alert(format);
JSFIDDLE DEMO
Hope it help:
var dateStart= new Date('1900-01-01');
var afterDay=42216;
var newDay=new Date(dateStart.getTime() + afterDay*24*60*60*1000);
alert(newDay);
I have one input type text:
<input type="text" id="policyholder-dob" name="policyholder-dob" />
I want to type number in this field in mm/dd/yyyy format:
like 01/01/2014
This is my js code but its not working, what mistake have I made?
function dateFormatter(date) {
var formattedDate = date.getDate()
+ '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
return formattedDate;
}
var nextduedate = $("#policyholder-dob").val();
var dateFormatDate = nextduedate.slice(0, 2);
var dateFormatMonth = nextduedate.slice(2, 4);
var dateFormatYear = nextduedate.slice(4, 8);
var totalFormat = dateFormatMonth + '/' + dateFormatDate + '/' + dateFormatYear;
var againNewDate = new Date(totalFormat);
againNewDate.setDate(againNewDate.getDate() + 1);
var todaydate = dateFormatter(againNewDate);
$("#policyholder-dob").prop("value", todaydate);
Any help will be really appreciated.
Thankfully, your input is consistently in this format:
mm/dd/yyyy
So you can convert it to a Date object through a custom function, such as:
function stringToDate(str){
var date = str.split("/"),
m = date[0],
d = date[1],
y = date[2],
temp = [];
temp.push(y,m,d);
return (new Date(temp.join("-"))).toUTCString();
}
Or:
function stringToDate(str){
var date = str.split("/"),
m = date[0],
d = date[1],
y = date[2];
return (new Date(y + "-" + m + "-" + d)).toUTCString();
}
Etc..
Calling it is easy:
stringToDate("12/27/1963");
And it will return the correct timestamp in GMT (so that your local timezone won't affect the date (EST -5, causing it to be 26th)):
Fri, 27 Dec 1963 00:00:00 GMT //Late december
Example
There are various ways to accomplish this, this is one of them.
I'd suggest moment.js for date manipulation. You're going to run into a world of hurt if you're trying to add 1 to month. What happens when the month is December and you end up with 13 as your month. Let a library handle all of that headache for you. And you can create your moment date with the string that you pull from the val. You substrings or parsing.
var d = moment('01/31/2014'); // creates a date of Jan 31st, 2014
var duration = moment.duration({'days' : 1}); // creates a duration object for 1 day
d.add(duration); // add duration to date
alert(d.format('MM/DD/YYYY')); // alerts 02/01/2014
Here's a fiddle showing it off.
I've got a string from an input field which I use for date with a format like this 25-02-2013. Now I want to compare the string with today's date. I want to know if the string is older or newer then today's date.
Any suggestions?
<script type="text/javascript">
var q = new Date();
var m = q.getMonth()+1;
var d = q.getDay();
var y = q.getFullYear();
var date = new Date(y,m,d);
mydate=new Date('2011-04-11');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
</script>
Exact date comparsion and resolved bug from accepted answer
var q = new Date();
var m = q.getMonth();
var d = q.getDay();
var y = q.getFullYear();
var date = new Date(y,m,d);
mydate=new Date('2011-04-11');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
You can use a simple comparison operator to see if a date is greater than another:
var today = new Date();
var jun3 = new Date("2016-06-03 0:00:00");
if(today > jun3){
// True if today is on or after June 3rd 2016
}else{
// Today is before June 3rd
}
The reason why I added 0:00:00 to the second variable is because without it, it'll compare to UTC (Greenwich) time, which may give you undesired results. If you set the time to 0, then it'll compare to the user's local midnight.
Using Javascript Date object will be easier for you. But as the Date object does not supports your format i think you have to parse your input string(eg: 25-02-2013) with '-' to get date month and year and then use Date object for comparison.
var x ='23-5-2010';
var a = x.split('-');
var date = new Date (a[2], a[1] - 1,a[0]);//using a[1]-1 since Date object has month from 0-11
var Today = new Date();
if (date > Today)
alert("great");
else
alert("less");
If your date input is in the format "25-02-2013", you can split the string into DD, MM and YYYY using the split() method:
var date_string="25-02-2013";
var day = parseInt(date_string.split("-")[0]);
var month= parseInt(date_string.split("-")[1]);
var year = parseInt(date_string.split("-")[2]);
The parseInt() function is used to make the string into an integer. The 3 variables can then be compared against properties of the Date() object.
The most significant points which needs to be remembered while doing date comparison
Both the dates should be in same format to get accurate result.
If you are using date time format and only wants to do date comparison then make sure you convert it in related format.
Here is the code which I used.
var dateNotifStr = oRecord.getData("dateNotif");
var today = new Date();
var todayDateFormatted = new Date(today.getFullYear(),today.getMonth(),today.getDate());
var dateNotif=new Date(dateNotifStr);
var dateNotifFormatted = new Date(dateNotif.getFullYear(),dateNotif.getMonth(),dateNotif.getDate());
Well, this can be optimized further but this should give you clear idea on what is required to make dates in uniform format.
Here's my solution, getDay() doesn't work like some people said because it grabs the day of the week and not the day of the month. So instead you should use getDate like I used below
var date = new Date();
var m = date.getMonth();
var d = date.getDate();
var y = date.getFullYear();
var todaysDate = formateDate(new Date(y,m,d));
console.log("Todays date is: " + todaysDate)
const formateDate = (assignmentDate) => {
const date = new Date(assignmentDate)
const formattedDate = date.toLocaleDateString("en-GB", {
day: "numeric",
month: "long",
year: "numeric"
})
return formattedDate
}
The function below is just to format the date into a legible format I could display to my users
<script type="text/javascript">
// If you set the timezone then your condition will work properly,
// otherwise there is a possibility of error,
// because timezone is a important part of date function
var todayDate = new Date().toLocaleString([], { timeZone: "Asia/Dhaka" }); //Today Date
var targetDate = new Date('2022-11-24').toLocaleString([], { timeZone: "Asia/Dhaka" });
console.log('todayDate ==', todayDate); // todayDate == 10/31/2022, 12:15:08 PM
console.log('targetDate ==', targetDate); // targetDate == 11/24/2022, 6:00:00 AM
if(targetDate >= todayDate)
{
console.log("Today's date is small");
}
else
{
console.log("Today's date is big")
}
</script>