0

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>
Community
  • 1
  • 1
Jon A
  • 137
  • 2
  • 11
  • can you give more info, what you actually want to do.. – Abhinav Feb 17 '17 at 08:33
  • Yeah, I want to compare datetime now with the time until first event starts. When it starts to display a basic notification that this event is on it's way. Sorry if my question is hard to understand – Jon A Feb 17 '17 at 08:34
  • you can get datetime now using new Date() whats problem you are facing... – Abhinav Feb 17 '17 at 08:36
  • I don't really know how to compare those 2 (datetime now with startdate and starttime from database), can you give me a basic e.g. please! – Jon A Feb 17 '17 at 08:37
  • I can but you need to share your piece of code where you are getting datetime from database and function where you want to compare those, what do you really expect from comparision.. – Abhinav Feb 17 '17 at 08:39
  • I wanted to do something like this but I don't know if it's quite right: "" – Jon A Feb 17 '17 at 08:41
  • For what I want with the comparison is to display basic notification about the event to come when the condition is meet. – Jon A Feb 17 '17 at 08:42
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/135936/discussion-between-user7417866-and-jon-a). – Abhinav Feb 17 '17 at 08:43
  • can you give me value of result you getting into Ajax, it should be your Json string .. "[{}]" – Abhinav Feb 17 '17 at 11:21

1 Answers1

1

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.. :)

Abhinav
  • 1,202
  • 1
  • 8
  • 12