Jquery How to check today time greater then use given time? - javascript

How to check time conditionin Jquery
var startTime="20:02:55"; // or 12:34
var endTime ="21:02:55" // or 1:34
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
if(time >startTime || time < endTiime){
$("#a").html("show Box");
}else{
$("#a").html("Expire BOx");
}
How to check 12 hour and 24 hour condition also?
is it correct? i need am, pm format check please can anyone help me?

Here is some code. I am appending to show both behaviour.
Here is DEMO
test("20:02:55", "21:02:55");
test("13:02:55", "15:02:55");
function test(start_time, end_time) {
var dt = new Date();
//convert both time into timestamp
var stt = new Date((dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear() + " " + start_time);
stt = stt.getTime();
var endt = new Date((dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear() + " " + end_time);
endt = endt.getTime();
var time = dt.getTime();
if (time > stt && time < endt) {
$("#a").append("<br> show Box ");
} else {
$("#a").append("<br> Expire BOx ");
}
}

Try this.
I took the logic to print 'Show Box' if the current time is in between the start and end time. else viceversa.
var startTime="20:02:55"; // or 12:34
var endTime ="21:02:55" // or 1:34
var dt = new Date();
var st = new Date('00','00','00',startTime.split(':')[0],startTime.split(':')[1],startTime.split(':')[2]);
var et = new Date('00','00','00',endTime.split(':')[0],endTime.split(':')[1],endTime.split(':')[2]);
if(dt.getTime() >st.getTime() && dt.getTime() < et.getTime()){
alert("show Box");
}else{
alert("Expire BOx");
}

Related

How is this variable still NULL

I'm in the process of writing a CasperJS script to automate a search form and capture the subsequent page. However, the search form goes to a loading splash page first until data arrives. So i added the waitForSelector function which seems to be working for some of my pages, but others return the variable name as NULL. How can that be if it is truly "waiting" for that element to be on the DOM?
casper.each(searchPages,function(casper,index){
var currentTime = new Date();
var month = currentTime.getMonth() + 2;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var dateStart = month + "/" + day + "/" + year;
month = currentTime.getMonth() + 3;
var dateEnd = month + "/" + day + "/" + year;
casper.thenOpen(url,function(){
var myfile = "data-"+year + "-" + month + "-" + day+".html";
this.evaluate(function(j) {
document.querySelector('select[name="searchParameters.localeId"]').selectedIndex = j;
},index);
this.evaluate(function(start) {
$("#leaveDate").val(start);
},dateStart);
this.evaluate(function(end) {
$("#returnDate").val(end);
},dateEnd);
this.evaluate(function() {
$("#OSB_btn").click();
});
this.waitForSelector('#destinationForPackage', function() {
var name = casper.evaluate(function() {
return $("#destinationForPackage option[value='" + $("#destinationForPackage").val() + "']").text()
});
if (name != "Going To"){
if (name == null){
console.log("it's null");
}else{
name = name.replace("/","_");
casper.capture('Captures/Searches/search_' + name + '.jpg');
console.log("Capturing search_" + name);
}
}
},function(){
console.log("Search page timed-out.");
},20000);
});
});
I was able to solve this by creating a recursive function if the element is still not available. Now i'm having a memory issue though, new question here => CasperJS running out of memory
casper.each(searchPages,function(casper,index){
loadSearch(casper,index);
});
function loadSearch(casper,index){
var currentTime = new Date();
var month = currentTime.getMonth() + 2;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var dateStart = month + "/" + day + "/" + year;
month = currentTime.getMonth() + 3;
var dateEnd = month + "/" + day + "/" + year;
casper.thenOpen(url,function(){
var myfile = "data-"+year + "-" + month + "-" + day+".html";
this.evaluate(function(j) {
document.querySelector('select[name="searchParameters.localeId"]').selectedIndex = j;
},index);
this.evaluate(function(start) {
$("#leaveDate").val(start);
},dateStart);
this.evaluate(function(end) {
$("#returnDate").val(end);
},dateEnd);
this.evaluate(function() {
$("#OSB_btn").click();
});
this.waitForSelector('#destinationForPackage', function() {
if (this.exists('#destinationForPackage')){
var name = casper.evaluate(function() {
return $("#destinationForPackage option[value='" + $("#destinationForPackage").val() + "']").text()
});
if (name != "Going To"){
if (name == null){
console.log("it's null");
}else{
name = name.replace("/","_");
casper.capture('Captures/Searches/search_' + name + '.jpg');
console.log("Capturing search_" + name);
}
}
}else{
console.log("Still doesn't exist...retry");
loadSearch(casper,index);
}
},function(){
console.log("Search page timed-out.");
},20000);
});
}

JavaScript clock not displaying properly

I'm trying to make an updating JavaScript clock on my webpage. The problem I'm having is that, while the value itself updates (I use alert(timeNow) to show the value and make sure it's updating), the clock on the website doesn't. I was just wondering if there was something I was missing, or if I've just happened to come across something that I can't quite do. I'd prefer if there was a way to do it using jQuery, as I understand that a little better than normal JavaScript.
Javascript:
function updateClock() {
var thisDate = new Date();
if (thisDate.getHours() > 11 && thisDate.getHours() != 0) {
var Hours = Math.abs(thisDate.getHours() - 12);
var AmPm = "PM"
} else {
var Hours = thisDate.getHours()
var AmPm = "AM"
}
if (thisDate.getMinutes() < 10) {
var Mins = "0" + thisDate.getMinutes();
} else {
var Mins = thisDate.getMinutes();
};
var timeNow = thisDate.getDate() + "/" + (thisDate.getMonth() + 1) + "/" + thisDate.getFullYear() + " " + Hours + ":" + Mins + " " + AmPm;
return timeNow;
};
setInterval(updateClock, 1000);
$("span#time").append(updateClock());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="time"></span>
You are not consuming the return value of updateClock function, thus the updated time is not reflecting.
You should update the text of time span
Use
setInterval(function(){
$("span#time").text(updateClock());
}, 1000);
You are returning the time in the function updateClock(). What you actually want to do is to set it into the DOM at the end of updateClock(). Here is an updated example:
function updateClock() {
var thisDate = new Date();
if (thisDate.getHours() > 11 && thisDate.getHours() != 0) {
var Hours = Math.abs(thisDate.getHours() - 12);
var AmPm = "PM"
} else {
var Hours = thisDate.getHours()
var AmPm = "AM"
}
if (thisDate.getMinutes() < 10) {
var Mins = "0" + thisDate.getMinutes();
} else {
var Mins = thisDate.getMinutes();
};
var timeNow = thisDate.getDate() + "/" + (thisDate.getMonth()+1) + "/" + thisDate.getFullYear() + " " + Hours + ":" + Mins + " " + AmPm;
$("span#time").text(timeNow);
}
setInterval(updateClock, 1000);
You could of course also just use the returned value of updateClock() to update the DOM. In this way, you would separate the DOM manipulation and the JavaScript time calculation. #Satpal described this way.
Try This...
$(document).ready(function()
{
goforit();
});
var dayarray=new Array ("Sunday","Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday")
var montharray=new Array("January","February","March","April","May","June",
"July","August","September","October","November","December")
function getthedate() {
d = new Date();
d.setUTCFullYear(2004);
d.setUTCMonth(1);
d.setUTCDate(29);
d.setUTCHours(2);
d.setUTCMinutes(45);
d.setUTCSeconds(26);
var mydate=new Date()
var year=mydate.getYear()
if (year < 1000)
year+=1900
var day=mydate.getDay()
var month=mydate.getMonth()
var daym=mydate.getDate()
if (daym<10)
daym="0"+daym
var hours=mydate.getHours()
var minutes=mydate.getMinutes()
var seconds=mydate.getSeconds()
var dn=""
if (hours>=12)
dn=""
if (hours>12){
hours=hours-12
}
if (hours==0)
hours=12
if (minutes<=9)
minutes="0"+minutes
if (seconds<=9)
seconds="0"+seconds
//Hire change font size
var cdate=""
+ mydate.toLocaleString()
+""
if (document.all)
document.all.clock.innerHTML=cdate
else if (document.getElementById)
document.getElementById("clock").innerHTML=cdate
else
document.write(cdate)
}
if (!document.all&&!document.getElementById)
getthedate()
function goforit()
{
if (document.all||document.getElementById)
setInterval("getthedate()",1000)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<SPAN id=clock style="display:block"></SPAN>
setInterval(function() {
$("span#time").text(moment(new Date()).format('DD/M/YYYY LTS'));
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script>
<span id="time"></span>

javascript - how to create countdown to date and time from sql server database?

It's my first time using a countdown in javascript so I have researched a little about this topic and I found some interesting links: "how to countdown to a date" and "https://www.sitepoint.com/build-javascript-countdown-timer-no-dependencies/", but my question is if I want to get data and time from the database, how can I do that? E.g.: I have a table Event with ID,Event,StartDate,StartTime and EndTime. How can I change from this: "var end = new Date('02/19/2012 10:1 AM');" from the first link or this: "Schedule the Clock Automatically" from the second to countdown time until event with the most recent time and date, and so on. Please keep in mind that I'm a total nooby so please bear with me. Sorry for any misspelling. Thank you!
Update:
This is the controller part: [HttpGet]
public JsonResult GetEvent(int Id)
{
BOL1.IMS2Entities db = new BOL1.IMS2Entities();
var ev = from e in db.tbl_Event
where e.ID == Id
select e;
//return Json(ev.FirstOrDefault(), JsonRequestBehavior.AllowGet);
return Json(Id, JsonRequestBehavior.AllowGet);
}
and this is the scripting part:
<script>
function GetEvent() {
debugger;
$.ajax({
type: "GET",
url: "Home/GetEvent",
data: { Id: ID },
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
debugger;
alert(result)
},
error: function (response) {
debugger;
alert('error');
}
});
}
var tbl_Event.StartDate = 'yyyy-MM-dd hh:hh:hh';
//var ServerDate_Time = '2017-02-17 10:45:00';
//console.log(CompareDateTime(ServerDate_Time));
console.log(CompareDateTime(tbl_Event.StartDate + tbl_Event.StartTime))
//function CompareDateTime (ServerDateTime){
function CompareDateTime (tbl_Event.StartDate + tbl_Event.StartTime){
var dateString = new Date();
var currentTime = new Date(parseInt(dateString));
var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
var day = ('0' + (currentTime.getDate())).slice(-2)
var year = currentTime.getFullYear();
var hours = ('0' + (currentTime.getHours())).slice(-2)
var min = ('0' + (currentTime.getMinutes())).slice(-2)
var sec = ('0' + (currentTime.getSeconds())).slice(-2)
var date = year + "-" + month + "-" + day + " " + hours + ":" + min + ":" + sec;
if(ServerDateTime == date){
return true;
}else {
return false;
}
}
}
</script>
assuming your datetime you are getting int tbl_Event.StartDate + tbl_Event.StartTime = 2017-02-17 10:45:00
this will go for your..
var ServerDate_Time = '2017-02-17 10:45:00';
console.log(CompareDateTime(ServerDate_Time));
function CompareDateTime (ServerDateTime){
var dateString = new Date();
var currentTime = new Date(parseInt(dateString));
var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
var day = ('0' + (currentTime.getDate())).slice(-2)
var year = currentTime.getFullYear();
var hours = ('0' + (currentTime.getHours())).slice(-2)
var min = ('0' + (currentTime.getMinutes())).slice(-2)
var sec = ('0' + (currentTime.getSeconds())).slice(-2)
var date = year + "-" + month + "-" + day + " " + hours + ":" + min + ":" + sec;
if(ServerDateTime == date){
return true;
}else {
return false;
}
}
Hope this helps....
Edit after your Edit ....
Updated code...
For Controller --
[HttpGet]
public JsonResult GetEvent(int id)
{
using (IMS2Entities ObjEntities = new IMS2Entities())
{
var ev = from e in ObjEntities.tblEvents
where e.id == id
select e;
return Json(ev.ToList(), JsonRequestBehavior.AllowGet);
}
}
JavaScript code for this
<script>
$(function () {
GetEvent(); // this will call GetEvent function once your DOM is ready, you can call this function on button click or anywhere as per your need.
function GetEvent() {
$.ajax({
type: "GET",
url: "/Home/GetEvent",
data: { Id: '1' }, // '1' is id for my sql database record which is passing to controller to bring back record from server.
success: function (result) {
// result will be collection of list return form server, since you are using id criteria it will always have only 1 record unless you have id as foreign key or something not primary/unique.
// I'm using only first instance of result for demo purpose, you can modify this as per your need.
alert(CompareDateTime(result[0].StartDateTime.substr(6))); // this will alert your true or false, as per I guess this will always return false, as your current date time will never match sql datetime. Still for your requirement.
},
error: function (response) {
alert(response);
}
});
}
function CompareDateTime (ServerDateTimeFormat){
// Convert ServerDateTimeFormat for Comparision
var ServerdateString = ServerDateTimeFormat;
var ServerCurrentTime = new Date(parseInt(ServerdateString));
var Servermonth = ('0' + (ServerCurrentTime.getMonth() + 1)).slice(-2)
var Serverday = ('0' + (ServerCurrentTime.getDate())).slice(-2)
var Serveryear = ServerCurrentTime.getFullYear();
var Serverhours = ('0' + (ServerCurrentTime.getHours())).slice(-2)
var Servermin = ('0' + (ServerCurrentTime.getMinutes())).slice(-2)
var Serversec = ('0' + (ServerCurrentTime.getSeconds())).slice(-2)
var Serverdate = Serveryear + "-" + Servermonth + "-" + Serverday + " " + Serverhours + ":" + Servermin + ":" + Serversec;
// Current Date Time for Comparision
var currentTime = new Date();
var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
var day = ('0' + (currentTime.getDate())).slice(-2)
var year = currentTime.getFullYear();
var hours = ('0' + (currentTime.getHours())).slice(-2)
var min = ('0' + (currentTime.getMinutes())).slice(-2)
var sec = ('0' + (currentTime.getSeconds())).slice(-2)
var date = year + "-" + month + "-" + day + " " + hours + ":" + min + ":" + sec;
if (date == Serverdate) {
return true;
}else {
return false;
}
}
});
</script>
Please make sure you put reference for JQuery before ... tag.
This is fully working example.. :)

Daily countdown timer - Display Message at 21:57

I'm struggling to figure out how Date() works, I found this on the web and wanted to make a countdown that stops at 21:57 UTC Time. It currently displays the message at 21:00 and apears until 22:00.
I tried to add if(currenthours != 21 && currentminutes >= 57){ and always broke it and got the message. I want it to stop 3 minutes before 22:00 and display the message. After it gets to 22:00 restart the countdown for the next day at 21:57.
Any help will be greatly appreciated !
var date;
var display = document.getElementById('time');
setInterval(function(){
date = new Date( );
var currenthours = date.getUTCHours();
// alert(currenthours);
var currentminutes = date.getUTCMinutes();
// alert(currentminutes);
var hours;
var minutes;
var secondes;
if (currenthours != 21) {
if (currenthours < 21) {
hours = 20 - currenthours;
} else {
hours = 21 + (24 - currenthours);
}
minutes = 60 - date.getUTCMinutes();
secondes = 60 - date.getUTCSeconds();
display.innerHTML = ('00' + hours).slice(-2) + ' HOURS ' + '<p>' +
('00' + minutes).slice(-2) + ' MINUTES ' + '</p>' +
('00' + secondes).slice(-2) + ' SECONDS';
} else {
display.innerHTML = "IT'S 21:57";
}
},1000);
<div id='time'></div>
Made a fiddle
https://jsfiddle.net/5qrs0tcp/1/
This is what I ended up with :
/*
|================================|
| COUNTDOWN TIMER |
|================================|
*/
// Return the UTC time component of a date in h:mm:ss.sss format
if (!Date.prototype.toISOTime) {
Date.prototype.toISOTime = function() {
return this.getUTCHours() + ':' +
('0' + this.getUTCMinutes()).slice(-2) + ':' +
('0' + this.getUTCSeconds()).slice(-2);
}
}
// Return the difference in time between two dates
// in h:mm:ss.sss format
if (!Date.prototype.timeDiff) {
Date.prototype.timeDiff = function(date2) {
var diff = Math.abs(this - date2);
return timeobj = {
hours : (diff/3.6e6|0), // hours
minutes : ('0' + ((diff%3.6e6)/6e4|0)).slice(-2), // minutes
seconds : ('0' + ((diff%6e4)/1e3|0)).slice(-2) // seconds
}
}
}
function countDown() {
var now = new Date();
var limitHr = 19;
var limitMin = 55;
var limitDate = new Date(+now);
// Set limitDate to next limit time
limitDate.setUTCHours(limitHr, limitMin, 0, 0);
// var msg = ['Currently: ' + now.toISOTime() + '<br>' + 'Limit: ' + limitDate.toISOTime()];
var msg = [];
var diff;
// If outside limitHr:limitMin to (limitHr + 1):00
if (now.getUTCHours() == limitHr && now.getUTCMinutes() >= limitMin) {
msg.push('Countdown stopped');
setTimeout(function(){
msg = ['Wait for it'];
var jsonCounter = {
stats : msg
}
jsonfile.writeFileSync(DailyGamePath, jsonCounter, {spaces: 3});
},5000);
var jsonCounter = {
stats : msg
}
jsonfile.writeFileSync(DailyGamePath, jsonCounter, {spaces: 3});
} else {
if (now > limitDate) limitDate.setDate(limitDate.getDate() + 1);
var jsonCounter = {
hours : now.timeDiff(limitDate).hours,
minutes : now.timeDiff(limitDate).minutes,
seconds : now.timeDiff(limitDate).seconds,
validating : msg
}
jsonfile.writeFileSync(DailyGamePath, jsonCounter, {spaces: 3});
}
}
setInterval(countDown, 1000);
var daily_status;
setTimeout( function(){
setInterval( function() {
jsonfile.readFile(DailyGamePath, (err, obj) => {
daily_status={
hours: obj.hours,
minutes: obj.minutes,
seconds: obj.seconds,
stats: obj.stats,
validating: obj.validating
};
return daily_status;
});
}, 1000);
}, 3000);
setTimeout( function(){
io.sockets.on('connection', (socket) => {
setInterval( function() {
// var GameStatus=DailyGameStatus();
socket.broadcast.emit('stream', {hours:daily_status.hours, minutes:daily_status.minutes, seconds:daily_status.seconds, stats:daily_status.stats, validating:daily_status.validating});
}, 1000);
});
}, 3000);
Date objects are very simple, they're just a time value and some handy methods.
I think your logic just needs to be:
if (currenthours != 21 && currentminutes < 57) {
// set the out of hours message
} else {
// time is from 21:57 to 21:59 inclusive
}
The countdown doesn't quite work because you're counting to 00 not to 57, but otherwise there doesn't seem to be an issue.
var date;
var display = document.getElementById('time');
setInterval(function(){
date = new Date( );
var currenthours = date.getUTCHours();
var currentminutes = date.getUTCMinutes();
var hours;
var minutes;
var secondes;
var limitHr = 5; // Change these to required values
var limitMin = 02; // Using 5:12 for convenience
var message = 'Currently: ' + date.toISOString() + '<p>';
// Create new message if outside limitHr:limitMin to limitHr:59 inclusive
if (currenthours != limitHr || currentminutes < limitMin) {
if (currenthours <= limitHr) {
hours = limitHr - currenthours;
} else {
hours = limitHr + (24 - currenthours);
}
minutes = limitMin - date.getUTCMinutes();
minutes += minutes < 0? 60 : 0;
secondes = 60 - date.getUTCSeconds();
message += ('00' + hours).slice(-2) + ' HOURS ' + '<p>' +
('00' + minutes).slice(-2) + ' MINUTES ' + '</p>' +
('00' + secondes).slice(-2) + ' SECONDS';
} else {
message += 'It\'s on or after ' + limitHr + ':' +
('0'+limitMin).slice(-2) + ' GMT';
}
// Display the message
display.innerHTML = message;
},1000);
<div id="time"></div>
Yes, the timer has issues but that wasn't part of the question. For a counter, it's simpler to just work in time differences, so I've added some methods to Date.prototype for ISO time (to be consistent with ISO Date) and time difference, then use those functions.
The function builds a Date for the end time so that calculations can use Date methods.
// Return the UTC time component of a date in h:mm:ss.sss format
if (!Date.prototype.toISOTime) {
Date.prototype.toISOTime = function() {
return this.getUTCHours() + ':' +
('0' + this.getUTCMinutes()).slice(-2) + ':' +
('0' + this.getUTCSeconds()).slice(-2) + '.' +
('00' + this.getUTCMilliseconds()).slice(-3) + 'Z';
}
}
// Return the difference in time between two dates
// in h:mm:ss.sss format
if (!Date.prototype.timeDiff) {
Date.prototype.timeDiff = function(date2) {
var diff = Math.abs(this - date2);
var sign = this > date2? '+' : '-';
return sign + (diff/3.6e6|0) + ':' + // hours
('0' + ((diff%3.6e6)/6e4|0)).slice(-2) + ':' + // minutes
('0' + ((diff%6e4)/1e3|0)).slice(-2) + '.' + // seconds
('00' + (diff%1e3)).slice(-3); // milliseconds
}
}
function countDown() {
var now = new Date();
var limitHr = 1;
var limitMin = 10;
var limitDate = new Date(+now);
// Set limitDate to next limit time
limitDate.setUTCHours(limitHr, limitMin, 0, 0);
var msg = ['Currently: ' + now.toISOTime() + '<br>' + 'Limit: ' + limitDate.toISOTime()];
var diff;
// If outside limitHr:limitMin to (limitHr + 1):00
if (now.getUTCHours() != limitHr || now.getUTCMinutes() != limitMin) {
if (now > limitDate) limitDate.setDate(limitDate.getDate() + 1);
msg.push(now.timeDiff(limitDate));
} else {
msg.push('It\'s after ' + limitHr + ':' + ('0'+limitMin).slice(-2));
}
document.getElementById('msgDiv2').innerHTML = msg.join('<br>');
}
window.onload = function() {
setInterval(countDown, 1000);
}
<div id="msgDiv2"></div>>
I've left the milliseconds in, round to seconds if you wish.
I've left the timer using setInterval, though I'd prefer to use setTimeout and manually calculate the time to just after the next full second so that it never skips. Most browsers using setTimeout will slowly drift so that they skip a second every now and then. Not really an issue unless you happen to see it, or compare it to the tick of the system clock.

Javascript Date constructor ignoring parameters

Supposedly, I should be able to create an arbitrary date using the Date constructor as demonstrated here and referenced here
Where am I going wrong? Please notice that on the last few lines of prettyDateToTimeStamp, I modify the month and day to verify that the Date constructor is doing something - but it is not noticing anything I pass in and just returns the current date.
Here is my code below: and a jsfiddle
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to display the full year of todays date.</p>
<p id="demo2">todays date.</p>
<p id="demo3">some other date.</p>
<button onclick="showdates()">Try it</button>
<script>
function showdates() {
var d = Date.now();
var dv = document.getElementById('demo');
dv.innerHTML = d;
var pd = prettyDate(d);
dv = document.getElementById('demo2');
dv.innerHTML = pd;
var ts = prettyDateToTimeStamp(pd);
dv = document.getElementById('demo3');
dv.innerHTML = ts;
}
function prettyDate(javaScriptTimeStamp) {
var dt = new Date(javaScriptTimeStamp);
var year = dt.getFullYear();
var month = dt.getMonth() + 1;
var day = dt.getDate();
var hours = dt.getHours();
var minutes = dt.getMinutes();
var seconds = dt.getSeconds();
return month + "/" + day + "/" + year + " " + hours + ":" + minutes + ":" + seconds;
}
function prettyDateToTimeStamp(prettyDate) {
var halves = prettyDate.split(' ');
console.log("halves: " + halves);
var calpart = halves[0];
console.log("calpart : " + calpart );
var clockpart = halves[1];
console.log("clockpart : " + clockpart );
var calbits = calpart.split('/');
console.log("calbits : " + calbits );
var timebits = clockpart.split(':');
console.log("timebits : " + timebits );
var year = parseInt(calbits[2],10);
console.log("year : " + year );
var month = parseInt(calbits[0],10);
console.log("month : " + month );
var day = parseInt(calbits[1],10);
console.log("day : " + day );
var hour = parseInt(timebits[0],10);
console.log("hour : " + hour );
var min = parseInt(timebits[1],10);
console.log("min : " + min );
var sec = parseInt(timebits[2],10);
console.log("sec : " + sec );
month += 3; // change month radically to demonstrate the problem
console.log("month is now: " + month );
day += 7; // change day too
console.log("day is now: " + day );
var ts = Date(year,month,day,hour,min,sec,0);
console.log("ts : " + ts ); // date ctor paramters completely ignored...?
return ts;
}
</script>
</body>
</html>
omg, I have to say "new" Date .... (I've been using Python too much lately)
corrected code now works.
function prettyDateToTimeStamp(prettyDate) {
var halves = prettyDate.split(' ');
var calpart = halves[0];
var clockpart = halves[1];
var calbits = calpart.split('/');
var timebits = clockpart.split(':');
var year = parseInt(calbits[2],10);
var month = parseInt(calbits[0],10);
var day = parseInt(calbits[1],10);
var hour = parseInt(timebits[0],10);
var min = parseInt(timebits[1],10);
var sec = parseInt(timebits[2],10);
month += 3; // change month radically to demonstrate the problem
day += 7; // change day too
var ts = new Date(year,month,day,hour,min,sec,0); // you have to use NEW here!
return ts;
}

Categories

Resources