sábado, 13 de septiembre de 2014

Crear reloj en pagina html 5 con javascript y formato de fecha personalizado

Una de las mayores complicaciones es poder dar fotmato propio a las fechas, y aumque existen infinitas librerias para ellos, muchas veces cargar tantas librerias hacen pesada nuestra aplicacion. A continuacion un ejemplo de como se puede embeber un reloj en un pagina web usando javascript y jquery para el uso de selecctores del DOM.



<!DOCTYPE html>
<html>
<head>
</head>

<script type="text/javascript">
//Funcion string.Format en javascript
if (!String.format) {
    String.format = function (format) {

        var args = Array.prototype.slice.call(arguments, 1);
        var sprintfRegex = /\{(\d+)\}/g;

        var sprintf = function (match, number) {
            return number in args ? args[number] : match;
        };

        return format.replace(sprintfRegex, sprintf);
    };
}

 //Timer
  var TimerClock = null;

    var monthNamesShort = new Array(Resources.Formated_monthNamesShort_January, Resources.Formated_monthNamesShort_Febrary, Resources.Formated_monthNamesShort_March,
        Resources.Formated_monthNamesShort_April, Resources.Formated_monthNamesShort_May, Resources.Formated_monthNamesShort_June, Resources.Formated_monthNamesShort_July,
        Resources.Formated_monthNamesShort_Augost, Resources.Formated_monthNamesShort_September, Resources.Formated_monthNamesShort_October,
        Resources.Formated_monthNamesShort_November, Resources.Formated_monthNamesShort_December);

    var dayNamesShort = new Array(Resources.Formated_dayNamesShort_Sunday, Resources.Formated_dayNamesShort_Monday, Resources.Formated_dayNamesShort_Tuesday,
        Resources.Formated_dayNamesShort_Wednesday, Resources.Fomated_dayNamesShort_Thursday, Resources.Formated_dayNamesShort_Friday, Resources.Formated_dayNamesShort_Saturday);

    $(document).ready(function () {
        startClock();
    });

    function startClock() {
        TimerClock = setInterval(function () {
             refreshFormatedTime();
        }, 1000);
    }

    function refreshFormatedTime() {
        var currentDate = new Date();
        var currentMonth = currentDate.getMonth();
        var currentDay = currentDate.getDay();
        var currentDateText = String.format("{0} {1} {2} {3}", dayNamesShort[currentDay], currentDate.format("dd"), monthNamesShort[currentMonth], currentDate.format("hh:mm:ss"));
        $("#lblDate").text(currentDateText);
    }

</script>
<body>
<div id="header">
<b>
<label id="lblDate" style="font-size: 14pt;"></label>
</b>
</div>
</body>
</html>

No hay comentarios:

Publicar un comentario