jquery get current time. TempusJS - working with dates in javascript


Another useful thing for sites is inserting the current date. There are dozens of examples of date scripts on the Internet, but many of them, in my opinion, are ponderous and, therefore, ugly. Meanwhile, using standard means JavaScript, you can insert the date on the site page very simply. I use it very often! In the picture (screenshot from the current site) estate "Skazka" !

Here is the whole date script:

In my opinion, nowhere is easier, quite beautiful and understandable. If you have no desire to study the construction of this script, then just paste it anywhere in the HTML page and get the following inscription:

Another more advanced option


! Today

It looks like this:

Today

In general, no skills are required, just stupidly insert the code and everything is ok!

More:

So let's start by assigning a date value to a variable d, then create arrays ( array) for days of the week ( day) and months ( month), indicating them in the required grammatical form: case, number, capital letter, if the word is at the beginning of the date, etc. The last line of the script is actually printing the date ( document.write). Here you set what and in what order you will display in the current date line. Components are separated from each other by the sign + . To enter a space, use the construction " " , and to enter the letter g (year) - construction " G."

As you can see from the script, getting data about the current time is performed by the element get. This method allows you to get the following information:

  • getDate()- returns a number from 1 to 31 representing the day of the month;
  • getDay()- returns the day of the week as an integer from 0 (Sunday) to 6 (Saturday);
  • getMonth()- returns the number of the month in the year;
  • getFullYear()- returns the year. If you simply use getYear(), then the current year minus 1900 will be displayed;
  • get Hours()- returns the hour of the day;
  • getMinutes()- returns minutes as a number from 0 to 59;
  • getSeconds()- returns the number of seconds from 0 to 59.

Insert directly Java-script inside the site page is not always convenient. It is better to put the script description at the top of the page between the tags and set a variable that we will call as needed in the text. Let's call her TODAY and define the date output form in it similarly to the above. The script will look like this:

To display the date, we call the script at the right place in the HTML code of the page using the following command:

If your site contains many pages where you need to show the date, it is more convenient to highlight Java- script for outputting the date to a separate file, for example, data.js. In practice, this is a page consisting of the first of the described scripts, that is, with the line document.write(see above). It must be located in the same directory as the main page, and called in the place where the date is displayed as follows:

Don't forget to check that the file data.js had the same encoding as the main document, otherwise the date will be displayed with wonderful hooks, squares and other gadgets.

Comment. It should be borne in mind that the described script displays the date set on the user's computer, which does not always correspond to the real current time. If you need to show the exact time, then you need to use a PHP script that will show the time on the server.

Getting the current date in JavaScript is very easy. This is what the Date object is for. Its syntax is quite simple and the method names are intuitive. In the examples below, I'll show you how to work with the Date object ( JavaScript new date) to get the current year, month, day and time to the nearest millisecond!

Getting the current date:

To get the current date in JavaScript, use the new keyword to create a new instance of the Date object.

var date = new Date(); console log(date);

This code prints the following information to the console:

//Tue Feb 02 2016 15:46:56 GMT-0500 (Eastern Standard Time)

It displays the current day of the week, current month, day of the month, year, and even the current time in 24-hour format. Fragment " GMT" means GMT time, and " -0500 ' is the difference in time zones between local time and GMT .

Quote from Wikipedia: "Greenwich Mean Time (GMT) GMT) is Mean Solar Time at the Royal Observatory, Greenwich, London." It's connected with UTC (UTC). « Eastern Standard Time The ' in the displayed date value refers to the time zone of your browser or computer.

* Please note that GMT and UTC are different. We will consider UTC values ​​in minutes.

* Also note that a date in JavaScript is defined by the time in milliseconds that has elapsed since midnight, January 01, 1970, UTC. There are 86,400,000 milliseconds in one day. The range of a Date object is -100,000,000 days to 100,000,000 days, relative to January 01, 1970 UTC.

* The values ​​obtained using the method mentioned above depend on the system settings of your device. If you change the computer's clock settings, the time returned by this method will also change.

Okay, we've got the new JavaScript Date formats out of the way and are now ready to move on!

Getting the day of the week:

To get the day of the week use the method JavaScript Date Object getDay() :

varday = date.getDay(); console log(day);

*Note that the days of the week are numbered from 0 to 6, Sunday = 0, Monday = 1, Tuesday = 2, and so on.

Get the month:

To get the current month of the current year, use the getMonth() method. Before that, I said that the names of the methods are intuitive!

var month = date.getMonth(); console log(month); //one

* Note that, like the days of the week, months are returned in a numeric format from 0 to 11; January = 0, February = 1, March = 2 and so on.

Getting the day of the month:

To get the day of the month, you can use the GetDate() method.

var dayOfMonth = date.getDate(); console log(dayOfMonth); //2

* The GetDate() method returns the days of the month, numbered from 1 to 31; number 1 corresponds to the first day of the month.

Getting time:

To get the current time, the GetTime() method is used.

vartime = date.getTime(); console log(time); //1454461242058

It looks... strange... What is it? You see the number of milliseconds that have passed since January 1, 1970 00:00:00 UTC. So how old is that?

1454461242058 ms / 31540000000 ms per year = about 46 years
1970 + 46 years = 2016

Let's check to make sure:

var year = date.getFullYear(); console.log(year) //2016

Yes, this is it! We just output the current date and time using JavaScript new date.

December 7, 2014 at 12:30

Date and time issues in JS

  • JavaScript

It is rare for a programmer to avoid working with dates and times. In general, date/time is a basic concept, and in most languages ​​there are built-in mechanisms for working with this data type. It would seem that JS is no exception, there is a built-in Date type, there are a bunch of functions in the prototype, however ...

Who is guilty
The first problem arises when you need to set the date / time in a time zone other than UTC and local. The Date constructor has no such parameter.

NewDate(); new Date(value); new Date(dateString); new Date(year, month[, day[, hour[, minute[, second[, millisecond]]]]]);
The only option where you can specify an offset relative to UTC is the third way. Calling the constructor in this format allows you to pass the offset as part of the string:

New Date("Sun Feb 01 1998 00:00:00 GMT+0700")
The string is accepted in the RFC2822 format, which is very inconvenient and difficult to manually enter. Getting such a string from user input is nearly impossible. I cannot imagine a person who would agree to enter a date in this format.

Despite the fact that in Date you can set all the parameters separately for the UTC time zone, this does not solve the problem - the time zone will remain local. But this is not the only problem.

The offset from UTC is not a constant. This is a function of the date, time (well, or from the timestamp, if you like) and, again, the time zone. For example, for Moscow, the latest time translation gives:

New Date(2014, 9, 25, 0, 0, 0); // 10/26/2014, 21:00:00 GMT+3 new Date(2014, 9, 27, 0, 0, 0); // 25.10.2014, 22:00:00 GMT+4
Thus, the constructor in the third option becomes practically useless, since the offset must be known in advance. And it, as was said, cannot be obtained so simply. The only library I've come across that uses Olson's database to calculate shifts is timezone-JS . The problem with using this library is that the underlying libraries (date/time pickers) know nothing about it and actively use the standard Date internally. Other libraries that work with the Date object do not explicitly refer to this database and do not receive updates from it. (Correct me in the comments.)

In a business application, timezones only make sense if the date and time are given. For example, if the working day starts at 9:00, then you are unlikely to expect that your colleague from Vladivostok will start working at 15:00. Timezones should not be taken into account, and in this case, the date must be displayed in UTC. However, in the case of regular events occurring at the same time in different time zones, a time zone is still needed. For example, your daily scrum starts at 10:00 for you and at 13:00 for Novosibirsk. By the way, this is exactly the difference between GMT and UTC. UTC is time without offset, and GMT is time with offset 0. Let me explain with an example:

12/31/2014, 20:59:59 GMT in the Moscow time zone should look like 12/31/2014, 23:59:59 :59
Because of this arithmetic, they are mostly confused. Unfortunately, this parameter is confused everywhere. The absence of a direct indication of the time zone in JS is treated as a local time zone, and the indication of UTC and GMT is equivalent.

In the situation, Intl could help. I could, but I don't have to. In particular, there is such a timeZone parameter, but, a little further, the standard defines: The time zone to use. The only value implementations must recognize is "UTC". Currently, apart from Chrome, no other browser supports arbitrary timezones.
With time ranges in JS, everything is really bad - there is nothing similar in the language. If you want to do well, do it yourself.

What to do
  • Option 1.
    Do not use custom timezone. The preferred option and probably the most painless. That is, you only have the local timezone and UTC. For these cases, all browsers seem to have everything, albeit not very convenient. In addition, the time zone is set globally for the OS and it is not kosher to change it for a specific web application.
  • Option 2.
    If arbitrary timezones are needed, do not use a timestamp. At all. Store the time in the savings bank in the RFC line with the time zone. I'm not sure if this will help defeat timezone shifts in a cross-browser sense, but at least Chrome is aware of such shifts.
  • Option 3.
    Situations are different and it happens that time is recorded in the database from any device. That is, in the form of a time stamp. There is nowhere to run, in order to correctly display the time, you need to know either the timezone of the device, or the timezone of the user, or both, and calculate all the shifts hand-to-hand. You can't do without using Olson's base.
  • There should be a moral to this fable, but I have nothing more to add yet. In the drafts of the ECMA standard, I do not observe any progress, probably there will not be any.

Date and time are part of our daily lives and therefore feature prominently in programming. In JavaScript, when creating a website, you might want to add a calendar, train timetable, or an interface for scheduling appointments. These apps should show the appropriate times based on the user's current time zone, or perform calculations related to the arrival and departure of an aircraft, or the start and end times of an event. In addition, you may need to use JavaScript to send daily reports at specific times or for filtering (for example, to find restaurants that are open at specific times).

date object

Date is a built-in JavaScript object that stores the date and time. It provides a number of built-in methods for formatting and manipulating this data.

By default, a new Date instance with no arguments creates an object with the current date and time, based on the current computer's system settings.

As an example, try assigning the current date to a variable. Create a now.js file.

// Set variable to current date and time
const now = new Date();
// view the output
now;
Wed Oct 18 2017 12:41:34 GMT+0000 (UTC)

The output is a date string containing the following data:

The date and time are broken up and displayed in a way that is easy to read.

However, JavaScript interprets a date based on a Unix timestamp, which is a value consisting of the number of milliseconds since midnight, January 1, 1970. You can get the timestamp using the getTime() method.

// Get the current timestamp
now.getTime();
1508330494000

The large number that appears in the output as the current timestamp is the number of milliseconds that have passed since midnight, January 1, 1970, to October 18, 2017.

Zero time (or epoch time) is represented by the date string 01 January, 1970 00:00:00 Universal Time (UTC) and a timestamp of 0. You can test this in the browser by creating a new variable in epoch.js and assigning it a new instance of Date , based on timestamp 0.

// Assign the timestamp 0 to a new variable
const epochTime = new Date(0);
epochTime;
January 01, 1970 00:00:00 Universal Time (UTC)

Zero time has been chosen as the standard for measuring time by computers, and this method is used in JavaScript. It is important to understand timestamps and date strings as these concepts can be used depending on the settings and purpose of the application.

Now you know how to create a new Date instance based on the current time and timestamp. There are four date formats in JavaScript in total. In addition to the default current time and timestamp, you can also use a date string or specify a specific date and time.

To demonstrate the different ways to refer to a specific date, try creating new Date objects that represent July 4, 1776, 12:30 GMT in three different ways.

// timestamp method
new Date(-6106015800000);
// date string method
new Date("January 31 1980 12:30");
// date and time method
new Date(1776, 6, 4, 12, 30, 0, 0);

All of these examples represent the same date and time information in three different ways.

As you can see, the timestamp method has a negative number; any date before zero time will be represented as a negative number.

In the third example, seconds and milliseconds are represented by 0. If you are missing any data when you create the Date object, you must assign it to 0. Missing data cannot be skipped because the order of the time data in the string does not change. It should also be noted that the month of July is marked here as 6, and not as 7. This is because the countdown starts from 0, not 1. More on this in the next section.

Retrieving a date with get

Once you have a date, you can access all of its components using various built-in methods. The methods return each part of the date relative to the local time zone. Each of these methods starts with get and returns a relative number. Below is a detailed table of get methods for the Date object.

Date Time Method Range Example
Year getFullYear() YYYY 1970
Month getMonth() 0-11 0 = January
Day of the month getDate() 1-31 1 = 1st of the month
Day of the week getDay() 0-6 0 = Sunday
Hour getHours() 0-23 0 = midnight
Minute getMinutes() 0-59
Second getSeconds() 0-59
Millisecond getMilliseconds() 0-999
timestamp getTime()

// Initialize a new birthday instance
const birthday = new Date(1980, 6, 31);

Now you can use all the methods to extract each component of the date.

birthday.getFullYear(); // 1980
birthday.getMonth(); // 6
birthday.getDate(); // 31
birthday.getDay(); // four
birthday.getHours(); // 0
birthday.getMinutes(); // 0
birthday.getSeconds(); // 0
birthday.getMilliseconds(); // 0
birthday.getTime(); // 333849600000 (for GMT)

Sometimes it may be necessary to extract only part of a date, and the built-in get methods will help you with this.

For example, you can compare today's date with October 3rd to see if it's October 3rd or not.

// Get today's date
const today = new Date();
// Compare today with October 3rd
if (today.getDate() === 3 && today.getMonth() === 9) (
console.log("It"s October 3rd.");
) else (
console.log("It"s not October 3rd.");
}
It's not October 3rd.

The built-in get methods allow you to access date components.

Changing the date with set

For all the get methods listed above, there is a corresponding set method. If get is used to retrieve a specific date component, set is used to change those components. Below is a detailed table of setter methods for the Date object.

Date Time Method Range Example
Year setFullYear() YYYY 1970
Month setMonth() 0-11 0 = January
Day of the month setDate() 1-31 1 = 1st of the month
Day of the week setDay() 0-6 0 = Sunday
Hour setHours() 0-23 0 = midnight
Minute setMinutes() 0-59
Second setSeconds() 0-59
Millisecond setMilliseconds() 0-999
timestamp setTime() Number of milliseconds since zero time

These set methods can be used to change one or more date components. For example, you can change the year in the birthday variable to 1997.

// Change year of birthday date
birthday.setFullYear(1997);
birthday;
Thu Jul 31 1997 00:00:00 GMT+0000 (UTC)

Now when you call the birthday variable, you see not 1980, but 1997.

The built-in set methods allow you to change different parts of the Date object.

UTC Methods

The get methods described above retrieve the date components based on the user's local time zone settings. To increase control over dates and times, you can use the getUTC methods, which work the same as the get methods, but calculate the time based on the UTC (Coordinated Universal Time) standard. Following is the table of UTC methods for Date object in JavaScript.

Date Time Method Range Example
Year getUTCFullYear() YYYY 1970
Month getUTCMonth() 0-11 0 = January
Day of the month getUTCDate() 1-31 1 = 1st of the month
Day of the week getUTCDay() 0-6 0 = Sunday
Hour getUTCHours() 0-23 0 = midnight
Minute getUTCMinutes() 0-59
Second getUTCSecons() 0-59
Millisecond getUTCMilliseconds() 0-999

To test the difference between local getters and UTC getters, run the following code.

// Assign current time to a variable
const now = new Date();
// Print local and UTC timezones
console.log(now.getHours());
console.log(now.getUTCHours());

This code will print the current time and time in UTC timezone. If you are currently in the UTC time zone, then the numbers that the program will display will be the same.

UTC provides an international time standard and can therefore support code according to time zones if your program needs it.

Conclusion

In this tutorial, you learned how to instantiate a Date object, how to use its built-in methods to access and modify the components of a given date. More information about time and date in JavaScript can be found on the Mozilla Developer Network.

Knowing how to work with dates is important for many common tasks in JavaScript, from generating regular reports to displaying dates and schedules in the correct time zone.

Tags:

JavaScript - Lesson 11. Date, representation and processing

In JavaScript, a date is defined as the number of milliseconds that have passed since January 1, 1970.

The built-in object is used to work with date and time Date. This object has no properties, but has several methods that allow you to set and change the date and time.

An object Date created with the operator new and constructor - Date.

For example:

var myData=new Date();

Variable value myData will be the current date and time:

Object Methods Date you can get separately the values ​​of the month, day of the week, hours, minutes and seconds:

  • getDate- returns a number between 1 and 31 representing the day of the month.
  • getHours- returns the hour of the day in the range from 0 (midnight) to 23.
  • getMinutes- returns minutes in the range from 0 to 59.
  • getSeconds- returns seconds in the range 0 to 59.
Suppose we want to write a script that will determine the current time and output it in the format "hh:mm:ss".

javascript date

Now let's write the function itself nTime():

function nTime(obj) ( var t=new Date(); var h=t.getHours(); var m=t.getMinutes(); var s=t.getSeconds(); var result=h+":"+m+ ":"+s; obj.res.value=result; )

* as you remember, methods are separated from the object by a dot, we talked about this in lesson 3 * As you can see, everything is simple. First, we determine the current time, and then, using methods, we extract individual values ​​of hours, minutes, and seconds from it.

Here I would like to clarify the line var result=h+":"+m+":"+s. For the first time, we were faced with the need to output both variable values ​​and plain text to the result. In principle, nothing complicated: variables are written as is, the text is taken in quotation marks, and the sign + performs the concatenation operation, i.e. their associations.

In our example, there was one flaw, we wanted the time to be displayed in the format "hh:mm:ss", and now it is displayed in the format "h:m:s". That is, at 5 am, the time will be displayed as "5:0:0", but I would like it like this: "05:00:00" (which is more familiar). For homework, you can try to fix this. For example, using the operator if and the string literal "0" (the idea is simple: if hours are less than 10, then in the result before h write "0" and so with all variables).

In the meantime, let's continue to study the methods of the object Date:

  • getDay- returns the day of the week as an integer from 0 (Sunday) to 6 (Saturday).
  • getMonth- returns the number of the month in the year, as an integer from 0 (January) to 11 (December).
  • getYear- returns the year as the last two digits ( getFullYear returns the year as four digits).

    * Unfortunately, since 2000, there is a problem with displaying the year in different browsers. The getYear method in IE displays the full year (instead of the last two digits), while FireFox displays 1XX instead of XX (i.e. substitutes 1). Therefore, it is preferable to use the getFullYear method.

Let's write a script that will determine the current date and output it in the format "day month year".

The html page code will be simple:

javascript date

Now let's write the function itself tData():

Function tData(obj) ( var s; var t=new Date(); var y=t.getFullYear(); var d=t.getDate(); var mon=t.getMonth(); switch (mon) ( case 0: s="January"; break; case 1: s="February"; break; case 2: s="March"; break; case 3: s="April"; break; case 4: s="May "; break; case 5: s="June"; break; case 6: s="July"; break; case 7: s="August"; break; case 8: s="September"; break; case 9 : s="October"; break; case 10: s="November"; break; case 11: s="December"; break; ) var result=d+" "+s+" "+y; obj.res.value =result; )

It turned out more authentic than in the first example, because I have to translate the names of the months into Russian.

The methods discussed above allow you to get the date. If we need to set the date, then the following methods should be used:

  • setDate- sets the day of the month in the range from 1 to 31.
  • setHours- sets the hour for the current time in the range from 0 (midnight) to 23.
  • setMinutes- sets the minutes in the range from 0 to 59.
  • setSeconds- sets the seconds in the range from 0 to 59.
  • setYear- sets the value of the year.
  • setMonth- sets the value of the month in the range from 0 (January) to 11 (December).
  • setTime- sets the value of an object Date and returns the number of milliseconds since January 1, 1970.
So, if we need to set the date to December 06, 2010, in the function we will have the following code:

Vart=new Date(); var y=t.setYear(2010); vard=t.setDate(6); varmon=t.setMonth(11); ...

You can set the date directly in the constructor by specifying the format string "month, day, year hours: minutes: seconds" as a parameter:

Var t=new Date("Feb, 10, 1975 5:45:10 PM");

Hours, minutes and seconds can be omitted (they will be zero):

Var t=new Date("Feb, 10, 1975");

The same date can be set using numbers, listing the year, month, day, hours, minutes, seconds separated by commas:

Var t=new Date(75, 1, 10, 17, 45, 10);

Or, omitting hours, minutes and seconds (they will be zero):

Var t=new Date(75, 1, 10);

* There is a problem: IE does not want to display the year, so it's better not to use these options.

That's all, you are quite ready to write a script yourself, which, when the page is loaded, will display the date, time and day of its visit (in normal Russian form). Good luck!







2022 gtavrl.ru.