Часы на HTML5 | Материалы сайта RUSELLER.COM

Бесплатный настраиваемый виджет часов для вашего сайта

Нужны точные часы для вашего сайта? Дата, время восхода и заката, долгота дня? Достаточно выбрать нужные параметры и скопировать код. И это бесплатно!

Настройки

Условия использования

  • Ссылка на Time.is должна быть явно видна на вашей странице. Можно перефразировать или перевести текст ссылки, тогда она должна включать в себя Time.is, время, название местоположения (Санкт-Петербург) либо название часового пояса (MSK). Приемлемые варианты текста ссылки: «Время в Санкт-Петербург», «Санкт-Петербург», «Время сейчас». Не допускается ссылка вида: «Нажмите здесь».
  • Ваша страница не должна автоматически обновляться.
  • Использование в приложениях и скриптах не допускается.
  • Виджет распространяется без каких-либо гарантий.
  • Виджет бесплатен, если основной темой вашего сайта не является этот виджет.
  • Time.is заблокирует ваш виджет, если эти условия не будут выполняться.

Дополнительные возможности

Есть два скрипта виджета: упрощённая версия, t.js, которая отображает только время, и основной скрипт виджета, ru.js, который может отображать время, дату, время восхода и заката, продолжительность дня. Основной скрипт виджета доступен на нескольких языках. Для других языков замените ru в названии скрипта на код нужного языка. (Например, pl.js для польского языка и tr.js для турецкого.)

Читайте также:  Параллакс
Параметр Допустимые значения Значение по умолчанию
template TIME, DATE, SUN TIME
time_format hours, minutes, seconds, 12hours, AMPM hours:minutes:seconds
date_format dayname, dname, daynum, dnum, day_in_y, week, monthname, monthnum, mnum, yy, year year-monthnum-daynum
sun_format srhour, srminute, sr12hour, srAMPM, sshour, ssminute, ss12hour, ssAMPM, dlhours, dlminutes srhour:srminute-sshour:ssminute
coords Широта и долгота местоположения. Требуется для отображения времени восхода, заката и долготы дня.
id Для определения местоположения и часового пояса на стороне сервера. Требуется, если название местоположения содержит не-ASCII буквы, и если вы изменили значение id HTML-элемента.
callback Необязательный параметр: название функции, которая будет вызываться каждую секунду с параметром template.

Названия параметров и их значения чувствительны к регистру. Можно использовать HTML и другое содержимое в параметрах template, time_format, date_format и sun_format.

Можно создать несколько часов следующим образом:

UTC time: 
New York sunrise time:
Tokyo sunrise time:
Find the current time for any location or time zone on Time.is!

Значения параметров time_format, date_format, sun_format и template наследуются, так что вам не нужно их повторять, если значение такое же, как и для ранее определённого виджета.

Источник

Часы для сайта

    Код скрипта нужно вставить между тегами . .

Код скрипта  function digitalClock() < var date = new Date(); var hours = date.getHours(); var minutes = date.getMinutes(); var seconds = date.getSeconds(); //* добавление ведущих нулей */ if (hours 
Вызов скрипта на странице  

12-часовой формат времени: AM/PM

12-часовой формат времени: AM/PM   

Примеры оформления простых часов для сайта

  1 2 3 

Цветные часы для сайта

   
: :

Часы + дата

Хорошо смотрятся на сайте часы совместно с датой оформленные в одну строку.
В Примере 5 к скрипту часы добавлен скрипт дата.
Вид строки оформляется средствами css под дизайн сайта.

5 Часы + дата   Сегодня:   ( ) 

Аналоговые часы для сайта

Виджеты Аналоговых часов для сайта

Виджет 1  Виджет 2  

Источник

Display Live Time and Date on HTML Page

Learn Algorithms and become a National Programmer

In this article, we have presented the HTML and JavaScript code to Display Live Time and Date on HTML Page. Javascript date object and HTML span element can be used to display the current date and time. By default Javascript use the browser's timezone to display time and date.

Live Time is:

  1. JavaScript Date Object + HTML, JS code
  2. Update Date And Time in Real Time
  3. Methods to get date and time
  4. Summary

Let us get started with Display Live Time and Date on HTML Page.

JavaScript Date Object + HTML, JS code

New Date() constructor is used to create date object.Current Date and Time is stored inside javascript variable.

Then using TextContent property the content of HTML span element is set with current and time. Unique ID is given to span tag so that we can use it on getElementById() method to dispaly the current date and time.

JavaScript Code

 `use strict` var datetime = new Date(); console.log(datetime); document.getElementById("time").textContent = datetime; //it will print on html page 

Demo
Date and Time is Thu Sep 30 2021 10:43:14 GMT+0530 (India Standard Time)

Update Date And Time in Real Time

Following is the code to update date and time in real time in a given interval:

`use strict`; function refreshTime() < const timeDisplay = document.getElementById("time"); const dateString = new Date().toLocaleString(); const formattedString = dateString.replace(", ", " - "); timeDisplay.textContent = formattedString; >setInterval(refreshTime, 1000); 

Methods to get date and time

It returns the day of the month between 1 - 31 according to the local time zone

 `use strict` var datetime = new Date().getDate(); console.log(datetime); // it will represent date in the console of developers tool document.getElementById("time").textContent = datetime; //it will print on html page 
  • Date.prototype.getday(): It returns the day of the week (0–6) for the specific date according to local time zone.
`use strict` var datetime = new Date().getDay(); console.log(datetime); // it will represent date in the console of developers tool document.getElementById("time").textContent = datetime; //it will print on html page 
  • Date.prototype.getFullYear(): It returns the year of the specified date according to the local time zone.
 `use strict` var datetime = new Date().getFullYear(); console.log(datetime); // it will represent date in the console of developers tool document.getElementById("time").textContent = datetime; //it will print on html page 
  • Date.prototype.getHours():
    It will return the hour(0-23) in the specific local time zone. Using getHours()
 `use strict` var datetime = new Date().getHours()+1; console.log(datetime); // it will represent date in the console of developers tool document.getElementById("time").textContent = datetime; // represent on webbrowser 
 `use strict` var datetime = new Date().getMilliseconds(); console.log(datetime); // it will represent date in the console of developers tool document.getElementById("time").textContent = datetime; // represent on html page 
  • Date.prototype.getMonth():
    It will return the month between 0- 11 in the specified date according to local time zone. for getting month between 1 - 12 ,You have to add 1.
 `use strict` var datetime = new Date().getMonth() + 1; console.log(datetime); // it will represent date in the console of developers tool document.getElementById("time").textContent = datetime; // represent on html page 
  • Date.prototype.toDateString():
    It will return the "date" portion of the Date as a human-readable string like Fri Oct 01 2021
`use strict` var datetime = new Date().toDateString(); console.log(datetime); // it will represent date in the console of developer tool document.getElementById("time").textContent = datetime; // represent on html page 
  • Date.prototype.toLocaleTimeString():
    It will return a string with a locality-sensitive representation of the time portion of this date, based on system settings.It will return string like
    12:42:15 AM
 `use strict` var datetime = new Date().toLocaleTimeString(); console.log(datetime); // it will represent date in the console of developers tool document.getElementById("time").textContent = datetime; // represent on html page 

Summary

  • Date and time created in JavaScript are represented with the Date object.
  • We can’t create "only date" or "only time".
  • Months are counted from zero.So Januaruy is zero month to get exact month add one.
  • Days of week in getDay() are also counted from zero.So Sunday is zero day to exact day add one.
  • Dates can be subtracted, giving their difference in milliseconds. That’s because a Date becomes the timestamp when converted to a number.
  • Use Date.now() to get the current timestamp fast.

With this article at OpenGenus, you must have the complete idea of Display Live Time and Date on HTML Page.

AASHISH

Источник

Часы с использованием HTML5

Простой скрипт позволяет создать часы, которые отображают реальный ход времени.

demosourse

Разметка HTML

Для создания часов потребуется очень простой код.

index.html

         

Часы на HTML5

Материалы сайта RUSELLER.COM

CSS

Код CSS для часов еще проще.

Все остальные правила из файла main.css касаются только оформления демонстрационной страницы.

JavaScript

js/script.js

// Внутренние переменные var canvas, ctx; var clockRadius = 250; var clockImage; // Функции рисования: function clear() < // Очистка поля рисования ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); >function drawScene() < // Основная функция drawScene clear(); // Очищаем поле рисования // Получаем текущее время var date = new Date(); var hours = date.getHours(); var minutes = date.getMinutes(); var seconds = date.getSeconds(); hours = hours >12 ? hours - 12 : hours; var hour = hours + minutes / 60; var minute = minutes + seconds / 60; // Сохраняем текущий контекст ctx.save(); // Рисуем изображение часов (как фон) ctx.drawImage(clockImage, 0, 0, 500, 500); ctx.translate(canvas.width / 2, canvas.height / 2); ctx.beginPath(); // Рисуем цифры ctx.font = '36px Arial'; ctx.fillStyle = '#000'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; for (var n = 1; n // Рисуем часовую стрелку ctx.save(); var theta = (hour - 3) * 2 * Math.PI / 12; ctx.rotate(theta); ctx.beginPath(); ctx.moveTo(-15, -5); ctx.lineTo(-15, 5); ctx.lineTo(clockRadius * 0.5, 1); ctx.lineTo(clockRadius * 0.5, -1); ctx.fill(); ctx.restore(); // Рисуем минутную стрелку ctx.save(); var theta = (minute - 15) * 2 * Math.PI / 60; ctx.rotate(theta); ctx.beginPath(); ctx.moveTo(-15, -4); ctx.lineTo(-15, 4); ctx.lineTo(clockRadius * 0.8, 1); ctx.lineTo(clockRadius * 0.8, -1); ctx.fill(); ctx.restore(); // Рисуем секундную стрелку ctx.save(); var theta = (seconds - 15) * 2 * Math.PI / 60; ctx.rotate(theta); ctx.beginPath(); ctx.moveTo(-15, -3); ctx.lineTo(-15, 3); ctx.lineTo(clockRadius * 0.9, 1); ctx.lineTo(clockRadius * 0.9, -1); ctx.fillStyle = '#0f0'; ctx.fill(); ctx.restore(); ctx.restore(); > // Инициализация $(function()< canvas = document.getElementById('canvas'); ctx = canvas.getContext('2d'); // var width = canvas.width; // var height = canvas.height; clockImage = new Image(); clockImage.src = 'images/cface.png'; setInterval(drawScene, 1000); // Циклическое выполнение функции drawScene >);

Готово!

Данный урок подготовлен для вас командой сайта ruseller.com
Источник урока: www.script-tutorials.com/html5-clocks/
Перевел: Сергей Фастунов
Урок создан: 23 Марта 2012
Просмотров: 48518
Правила перепечатки

5 последних уроков рубрики "HTML и DHTML"

Лайфхак: наиполезнейшая функция var_export()

При написании или отладки PHP скриптов мы частенько пользуемся функциями var_dump() и print_r() для вывода предварительных данных массив и объектов. В этом посте я бы хотел рассказать вам о функции var_export(), которая может преобразовать массив в формат, пригодный для PHP кода.

17 бесплатных шаблонов админок

30 сайтов для скачки бесплатных шаблонов почтовых писем

Создание шаблона для письма не такое уж простое дело. Предлагаем вам подборку из 30 сайтов, где можно бесплатно скачать подобные шаблоны на любой вкус.

Как осуществить задержку при нажатии клавиши с помощью jQuery?

К примеру у вас есть поле поиска, которое обрабатывается при каждом нажатии клавиши клавиатуры. Если кто-то захочет написать слово Windows, AJAX запрос будет отправлен по следующим фрагментам: W, Wi, Win, Wind, Windo, Window, Windows. Проблема?.

Источник

Оцените статью