Showing posts with label datetime. Show all posts
Showing posts with label datetime. Show all posts

Working with Date and Time in JavaScript

If you have a requirement to get ShortDate (1/11/1900) and AM/PM time down to the second (2:12:27 PM) from a JavaScript Date object; use this Date prototype method "formatMMDDYYYY()" on the Date object:

 Date.prototype.formatMMDDYYYY = function(){  
 return (this.getMonth() + 1) +  
 '/' + this.getDate() +  
 '/' + this.getFullYear();  
 }  
 var time = new Date();  
 console.log(time.formatMMDDYYYY() + ' ' +  
 time.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: true })  
 );  

Say we want to calculate the number of days between two given dates. We can utilize this .js function:

 function getDays(firstDate,secondDate){  
  var startDay = new Date(firstDate);  
  var endDay = new Date(secondDate);  
  var millisecondsPerDay = 1000 * 60 * 60 * 24;  
  var millisBetween = startDay.getTime() - endDay.getTime();  
  var days = millisBetween / millisecondsPerDay;  
  // Round down.  
  return Math.floor(days);  
 }  
 alert(getDays(Date(), '1/1/2017'));  

Also, although not referenced above because I wanted to show pure/plain .js in the example, there are several .js libraries for Date operations. The most popular of which seems to currently be: https://momentjs.com/

Reference: https://stackoverflow.com/questions/2035699/how-to-convert-a-full-date-to-a-short-date-in-javascript/2035706

Useful T-SQL Dates Reference

For short US datetime format use this:

select convert(varchar, getDate(), 1) --10/15/2017

For a list of most others (SQL Server), see: https://rauofthameem.wordpress.com/2012/09/14/sql-date-time-conversion-cheat-sheet/

On to the useful SQL dates:

select dateadd(mm, datediff(mm, 1, getDate()), 0) as FirstaTheMonth

select dateadd(ms, -3, dateadd(mm, datediff(m, 0, getDate()) + 1, 0)) as LastaTheMonth

select dateadd(qq, datediff(qq, 0, getDate()), 0) as FirstDayOfQtr

select dateadd(wk, datediff(wk, 0, dateadd(dd, 6 - datepart(day, getDate()), getDate())), 0) --(First Monday of Month)





Great T-SQL References:

http://www.gehbeez.com/sql-get-first-and-last-day-of-a-week-month-quarter-year/

http://brianvanderplaats.com/cheat-sheets/T-SQL-Cheat-Sheet.html