Monday 6 August 2012

Convert the date time to timestamp and Compare the two datetime (dates) functions in Javascript.

Convert the date time to timestamp in Javascript. similar to strototime() function in php.
// Convert the date time to timestamp in Javascript. similar to strototime() function in php.
function convert_datetime_to_timestamp(date)
{
 var datetime = date.split(" ");
 date = datetime[0];
 time = datetime[1];

 d1 = date.split("-");
 y = d1[0];
 m = d1[1];
 d = d1[2];

 t1 = time.split(":");
 h = t1[0];
 i = t1[1];
 s = t1[2];

 //datetime = m + ' ' + d + ',' + y + ' ' + h + ':' + i + ':'+s;
var date = new Date(y, m, d, h, i, s, '0'); (works both on FireFox and Chrome Browers).
 
 return date.getTime();
}
// Compare the two datetime (dates) in Javascript.
/*  This below function compares two dates with a gap time as 6 Hours.
 @param date1 = '2012-08-06 14:9:19'
 @param date2 = '2012-08-06 20:9:19' 
 @return If errors found, return errors else null (if no errors) found. 
*/
function compare_two_dates(date1, date2)
{
 var error = '';
 
 if ( (date1 != "") || (date2 != "") )
 {
  // Check the dates time here;
  var minutes=1000*60;
  var hours=minutes*60;
  var days=hours*24;
  var years=days*365;
  
  now = new Date();
  current_time= now.getTime();
  
  // Check the dates time here;
  start_time= convert_datetime_to_timestamp(date1);
  expiry_time= convert_datetime_to_timestamp(date2);
  
  gap_hr = 6; // Minimum Gap between two dates is set as 6 Hrs. 
  gap_time= gap_hr*hours;
  diff_time= expiry_time - start_time;
  diff_mm= (diff_time)/minutes;
  diff_hr= Math.round(diff_time/hours);
  
  if ( (current_time >= start_time) && (current_time >= expiry_time))
   error = 'Date Available AND/OR Expiry time should be greater than current time.';

  else if ( (diff_time == 0) || (gap_time > diff_time) )
   error = 'Date Expires should be at least ' + gap_hr + ' hours greater than Date Available time.';
  
  //error = error + ' NowT: '+current_time+' DS: ' + start_time + ' DE: '+ expiry_time+' Diff: ' +diff_time+ ' DMM: ' + diff_mm+ ' DHR: '+diff_hr+' TG: '+gap_time;  
 }
 else {
  error =  'Enter both dates';
 }
 
 return error;
}

For more information about dates, please, check: JavaScript Date Object, JavaScript setDate() Method

No comments:

Post a Comment

Please post any queries and comments here.