<!DOCTYPE html>
<html>
<head>
<title>DotNetPeTips-JavaScript</title>
</head>
<body>
<script>
var second, first;
first = new Date("2020-05-02");
second = new Date("2020-04-02");
var days = Math.round((first - second) / (1000 * 60 * 60 * 24));
document.write("<br>Difference: " + days);
</script>
</body>
</html>
Difference between two dates in minute, hours javascript
we can also write a common logic so that it calculate difference in milliseconds ,days,hours and minutes.
<script>
var todaydate = new Date();
//adding one to the current year
var nextyear = todaydate.getFullYear() + 1;
//create date object for future date
var futuredate = new Date(nextyear + "-01-01");//which is next year newyear date
//subtracting both date
var milliseconds = (futuredate - todaydate); // milliseconds between now & future date which new year date
var days = Math.floor(milliseconds / 86400000); // days
var hours = Math.floor((milliseconds % 86400000) / 3600000); // hours
var minutes = Math.round(((milliseconds % 86400000) % 3600000) / 60000); // minutes
document.write("<br>" + days + " days " + hours + " hours " + minutes +" minutes until newyear");
</script>
Let’s take a real-time time example, let’s say I want to calculate my age in days, hours, and minutes.
then how we can achieve that task? please see below the code.
<!DOCTYPE html>
<html>
<head>
<title>AppsloveWorld-JavaScript</title>
</head>
<body>
<script>
var todaydate = new Date();
//adding one to the current year
//create date object for my dob
var dob = new Date("1992-01-25");//my dob date in yyyy-dd-mm
//subtracting both date
var milliseconds = (todaydate - dob); // milliseconds between now & future date which new year date
var dobdiffdays = Math.floor(milliseconds / 86400000); // days
var dobdiffhours = Math.floor((milliseconds % 86400000) / 3600000); // hours
var dobdminutes = Math.round(((milliseconds % 86400000) % 3600000) / 60000); // minutes
document.write("<br>My Age : " + dobdiffdays + " days " + dobdiffhours + " hours " + dobdminutes + " minutes");
</script>
</body>
</html>
Output
date
Nowadays, their public date and time are shown in the articles of all the famous websites because technology is changing very fast.
That’s why it is necessary to do this and it is also useful, this is an era of change, in this, the incidents are happening fast, millions of articles are published on the internet in a day, so you have to manage these articles and show them at the right time. It is necessary to know the time and date
The date and time tell the user whether the information is old or not, for example, an article written 5 years ago from today is not necessarily useful in the present time, so it is important for you.
That the date and time should be shown to the user so that the user can decide whether the given information is useful for him or not.
JavaScript provides a date object to show you date and time-related information, along with this object you have some built-in properties and methods.
By using these properties and methods, you can perform date and time-related operations on the webpage.
There may be many other situations in which you can use date object, such as if you want to store information about the complete activity of the user, then you can do it through date object, user login time, logout time. If the user has made an update, then you can also store that time through the date object.
Creating javascript date object
The date object has to be constructed, you cannot use it directly, so a date object is created by the new keyword, you can create the date object in 4 ways.
In the first method, you create a normal date object and do not pass any value in it, whose general syntax is being given to you below.
var objectName=new Date();
In the above syntax, a normal object will be created, will show the day, date, time, and standard time zone.
In a second way, while creating the date object, you can pass milliseconds while creating the object.
var objectName=new date(milliseconds);
In a third way, while creating the date object, you can pass it as a date and time string, by doing this, the date object will show the same date and time, whose general syntax is being given below.
var objectName=new
Date("date/month/year
hour:minute:seconds”);
In a fourth way, while creating the date object, you can pass date object by separating the year, month, day, hours, minutes, second, milliseconds from the comma respectively, whose syntax is being given below.
var objectName=new date(year,month,day,hours,minutes,seconds,millisecond);
javascript date object property
Javascript provides you 2 properties with date object
constructor – this property returns the function by which the date object has been created
prototype – By this property you add your custom properties and method to the object
javascript date object method
Below are some built in methods available with the date object.
getDate()
This method returns the current day between 1 to 31, you call it with the date object, whose example is being given below.
<script type="text/javascript">
var datebj = new Date();
var dayofdateobj = datebj.getDate();
document.write("<br>dayofdateobj: " + dayofdateobj);
</script>
getDay()
This method returns the current day from 0 to 6 for example if today is Thursday then this method will return 4 whose example is being given below.
<script type="text/javascript">
var datebj = new Date();
var Day = datebj.getDay();
document.write("<br>Day: " + Day);
</script>
getFull Year()
This method returns you the year, if the date object is initialized with a string date, then this object will return the same year, otherwise the current year will be shown, example is given to you below.
<script type="text/javascript">
var datebj = new Date();
var FullYear = datebj.getFullYear();
document.write("<br>FullYear: " + FullYear);
</script>
Similarly, JavaScript provides you more methods to use with the date object, the list of all the methods is being given below.
- getHours()
- getMinutes()
- getSeconds()
- getMilliseconds()
- getMonth()
- getTime()
The post [Solved]-How to get days,minute, hours between two dates in JavaScript? appeared first on Software Development | Programming Tutorials.
Read More Articles
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- jQuery Ajax GET Example with Parameters
- How to Pass Parameters in AJAX POST?| JQuery Ajax Post Json Example
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- How to add, edit and delete rows of an HTML table with Jquery?
- Registration form with image upload in MVC using jquery Ajax
- How to make an Inline editable table in MVC using jquery?
- Insert Update Delete Using Jquery Ajax and Modal Popup in Mvc
- [Solved]-How to Upload pdf file using jquery MVC?
- Dynamically creating graphs with jQuery
- Get all nodes on page except for those that have a specific node as an ancestor
- Sum numbers returns NaN
- jQuery off() and bind(this)
- How do i get column values of all checked rows?
- Caroufredsel image slider - get the number of the visible slide
- How to convert url to hyperlink using this script?
- Getting StackOverFlow Exception in ASP.NET C#
- removeEventListener onfocusout after pressing enter on input tag - error undefined
- Intercept click-event on Google Calendar with jquery
- jQuery: Return data after ajax call success is empty in Safari
- Making a callback in a chain?
- Jquery Each function,show values in div
- jquery animate top doesn't work
- jquery dynamic stracture with Eq
- id/class based selector v/s forms based selectors
- Javascript for every single page?
- Checking if a document is ready
- Italic tags are showing up
- CSS3 3d Flip with Jquery
- SAPUI5: How to bind a click event to horizontal layout?
- display:none not working properly
- jQuery Selectors and $(this)
- extract json.stringify(data)
- jquery validation: password change and confirmation
- jQuery don't run on my local server
- Pass multiple elements to an each function
- Create a function to change text color
- Get a variable inside an event function of a jquery plugin
- How to change <input type="text"> to <tr> using jquery
- Cannot handle file upload in Django when request comes from Ajax and a form
- Jquery - effect + autohide
- css change after jquery animation
- problem with jqgrid in jequery in asp.net mvc
- Extract Substring from jQuery Selector
- Javascript - Remove class with document.addEventListener not working
- Google Appengine & jQuery: Error 414 (Requested URI too long)
- Passing custom error code to ajax error function
- jquery comparing 2 integers
- What is the proper way to use my own theme (style) design and icons using jQuery Mobile powered website?
- getting Cannot read property 'done' of undefined from ajax call
- Trying to pass string as function argument to SVG
- escape sequence javascript
- Changing style with JQUERY is not working
- Clear Input Field Except for Submit Button
- check all jquery not working for dynamically populated checkbox
- Click handler is not firing on dynamically inserted elements
- Image gallery with relevant text in another div in query
- jquery text function - how to pass on the current value of the selected element
- how to alert the values of this array from DOM
- MVC 3 using dropdownlist and ajax to get a new model
- Jquery DOM Manipulation Somenthing better than that?
- How to make jQuery UI accordion toggle
- how can i use json explict function ? to pull the data fom different sites
- JSON data if/else parse
- How to check value already exist for a day in fullCalendar
- Using jQuery AJAX to update table of mysql
- Avoiding async: false; in jQuery AJAX within a function
- Make sure at least 1 checkbox is checked for multiple groups of checkboxes?
- setting values [jquery or javascript]
- JSON file does NOT display through the data.responseText. Although in Chrome, it's there in the debugger nicely
- alert() does not work for ajax error function
- Ajax cannot display json data from php. What's wrong with json format?
- How to delete the (X) at the top right side of fancy box
- how to match javascript onSubmit with jQuery submit?
- Isotope filtering with bootstrap
- jQuery, Javascript: Responsive site - execute function below 480px
- Jquery get parent id
- Array Serialization Issue
- jQuery validate for multiselect works only on double click
- Jquery ReferenceError: invalid assignment left-hand side
- WebSockets error on close
- Out of memory at line 12
- Use JQuery to modify CSS for content in an iFrame
- AJAX form executes PHP script but returns error
- $.inArray not worting on object JavaScript object any alternative?
- Jquery animate background code not working!
- jQuery DataTable Not a Function
- Add a 'data-toggle' attribute to a button in javascript
- jQuery - Accordion (De-Collapse)
- Show a pop-up that contains details of every row in html table
- Changing the image src Nested Inside Div
- How to get previous element from click target?
- Does jQuery have a on/live hover function for mouseenter or mouseout?
- jQuery Append events issue
- Organizing <pre> Tag Layout
- Put chart.js chart inside JQuery tooltip?
- How to Progressively highlight a chunk of text using jquery/js/css
- Jquery variable not set
- jQuery var not entering function
- jquery load not working in IE8
- Jquery javascript - Chained Select Tutorial with fiddle
- Javascript Color Selector to change Background Color
- chart.js Legends issue (not showing)
- Apply css on enabled buttons JavaScript
- JQuery File upload dialog not returning back to dialog from MVC Controller action
- How to SetVariable in jQuery
- jQuery - Toggle CSS Background Image Expand/Close
- Jquery: Multiple Content with a single Selector?
- How to include the session information in jQuery in ruby on rails?
- javascript countdown with start/stop/reset and input time from user
- jQuery check if URL contains string
- How to reference elements added by jQuery .append()
- How to select all items in a list using jQuery Selector
- Why is jquery Mega Menu so slow to load?
- JQuery effects behind the scenes
- IE compatibly mode JavaScript function not called
- jquery, how to use multiple ajax requests?
- Fetching from title attribute
- Same form, multiple times on page passing first form data to JQuery everytime
- Trigger an href event only before the onclick
- Validating DOM Elements
- Clear list with jquery on click
- load specific div in modal window using fancybox
- Using Javascript is there a way to grab the background image rendered by a linear or radial gradient?
- How I can use mouse events with Jquery
- Accessing variables after asynchronous jQuery getJSON calls
- Return value from js enclosing function in ajax
- jquery how to add and remove alert number in page title?
- Unknown Uncaught Type Error in Jquery/ASP
- Firefox fires keyup event twice
- show loader when ajax is working
- Ajax POST to PHP - How do I do a reply?
- Animated PNG to canvas
- Passing two parameters to a function
- Using each() to iterate through multiple ul's and hiding any child li's greater than 8
- Getting Request Parameter for Asynchronous Requests with Deferred Objects
- JQGrid confirmation box post saving edited data
- jquery- adding rows based on css property
- Active drop down links
- Link button will not work with JQuery modal form
- send image in http response to ajax response getting error imagefilefield is not JSON serializable
- using jquery to hide / show links based on checkbox
- Double trigger for jquery action
- Set class on a tag after click
- jQuery Datatables performance
- disable a inputfield on clicking a checkbox
- Remove last dynamically added row
- How to solve this JavaScript scope issue
- jquery slider breaks on page refresh
- How to remove the existence of a div with fadeout and delay functions in jquery
- I can't make a jQuery UI accordion tab change colors when used (like a:visited), can I?
- convert hsla to rgba by javascript or jquery
- Replace on Array In Jquery without using loop
- Can't break out of a javascript for loop
- How to count div's of one class, that are children of container div's of one class?
- Alternate between URLs for each onclick of href
- jQuery prependTo selector string
- jquery multiple toggle on IE
- How to dynamically add elements via jQuery
- $.mobile.ajaxEnabled = false;