Question

cutting down my JS file!

Asked by: blaadom

Hi,

Im looking to cut down this javascript file a lot but im not quite sure how to go about it? there are a lot of repeating features in the code so im assuming its possible..... any ideas on how i could do this? as much help as possible would be appreciated as im new to the javascript game :)

var monthAbbreviations = new Array("January ", "February ", "March ", "April ", "May ", "June ", "July ", "August ", "September ", "October ", "November ", "December ");
var daysOfTheWeek = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");

//TIME In milliseconds:
//MINUTES
ONEMINUTEAGO = -60000;
TWOMINUTESAGO = -120000;
THREEMINUTESAGO = -180000;
FOURMINUTESAGO = -240000;
FIVEMINUTESAGO = -300000;
SIXMINUTESAGO = -360000;
SEVENMINUTESAGO = -420000;
EIGHTMINUTESAGO = -480000;
NINEMINUTESAGO = -540000;
TENMINUTESAGO = -600000;
ELEVENMINUTESAGO = -660000;
TWELVEMINUTESAGO = -720000;
THIRTEENMINUTESAGO = -780000;
FOURTEENMINUTESAGO = -840000;
FIFTEENMINUTESAGO = -900000;
SIXTEENMINUTESAGO = -960000;
SEVENTEENMINUTESAGO = -1020000;
EIGHTEENMINUTESAGO = -1080000;
NINETEENMINUTESAGO = -1140000;
TWENTYMINUTESAGO = -1200000;
TWENTYONEMINUTESAGO = -1260000;
TWENTYTWOMINUTESAGO = -1320000;
TWENTYTHREEMINUTESAGO = -1380000;
TWENTYFOURMINUTESAGO = -1440000;
TWENTYFIVEMINUTESAGO = -1500000;
TWENTYSIXMINUTESAGO = -1560000;
TWENTYSEVENMINUTESAGO = -1620000;
TWENTYEIGHTMINUTESAGO = -1680000;
TWENTYNINEMINUTESAGO = -1740000;
THIRTYMINUTESAGO = -1800000;
THIRTYONEMINUTESAGO = -1860000;
THIRTYTWOMINUTESAGO = -1920000;
THIRTYTHREEMINUTESAGO = -1980000;
THIRTYFOURMINUTESAGO = -2040000;
THIRTYFIVEMINUTESAGO = -2100000;
THIRTYSIXMINUTESAGO = -2160000;
THIRTYSEVENMINUTESAGO = -2220000;
THIRTYEIGHTMINUTESAGO = -2280000;
THIRTYNINEMINUTESAGO = -2340000;
FOURTYMINUTESAGO = -2400000;
FOURTYONEMINUTESAGO = -2460000;
FOURTYTWOMINUTESAGO = -2520000;
FOURTYTHREEMINUTESAGO = -2580000;
FOURTYFOURMINUTESAGO = -2640000;
FOURTYFIVEMINUTESAGO = -2700000;
FOURTYSIXMINUTESAGO = -2760000;
FOURTYSEVENMINUTESAGO = -2820000;
FOURTYEIGHTMINUTESAGO = -2880000;
FOURTYNINEMINUTESAGO = -2940000;
FIFTYMINUTESAGO = -3000000;
FIFTYONEMINUTESAGO = -3060000;
FIFTYTWOMINUTESAGO = -3120000;
FIFTYTHREEMINUTESAGO = -3180000;
FIFTYFOURMINUTESAGO = -3240000;
FIFTYFIVEMINUTESAGO = -3300000;
FIFTYSIXMINUTESAGO = -3360000;
FIFTYSEVENMINUTESAGO = -3420000;
FIFTYEIGHTMINUTESAGO = -3480000;
FIFTYNINEMINUTESAGO = -3540000;
SIXTYMINUTESAGO = -3600000;
//HOURS
ONEHOURAGO = -3599999;
TWOHOURSAGO = -7200000;
THREEHOURSAGO = -10800000;
FOURHOURSAGO = -14400000;
FIVEHOURSAGO = -18000000;
SIXHOURSAGO = -21600000;
SEVENHOURSAGO = -25200000;
EIGHTHOURSAGO = -28800000;
NINEHOURSAGO = -32400000;
TENHOURSAGO = -36000000;
ELEVENHOURSAGO = -39600000;
TWELVEHOURSAGO = -43200000;
THIRTEENHOURSAGO = -46800000;
FOURTEENHOURSAGO = -46860000;
FIFTEENHOURSAGO = -46920000;
SIXTEENHOURSAGO = -46980000;
SEVENTEENHOURSAGO = -47040000;
EIGHTEENHOURSAGO = -47100000;
NINETEENHOURSAGO = -47160000;
TWENTYHOURSAGO = -47160000;
TWENTYONEHOURSAGO = -47220000;
TWENTYTWOHOURSAGO = -47280000;
TWENTYTHREEHOURSAGO = -47340000;
TWENTYFOURHOURSAGO = -47400000;
//DAYS
ONEDAYAGO = -86400000;
TWODAYSAGO = -172800000;
THREEDAYSAGO = -259200000;
FOURDAYSAGO = -345600000;

function dateReference(dateString) {
  var relative = relativeDate(dateString);
  var explicit = explicitDate(dateString, true);
  if (relative != explicit) {
    document.write("<acronym title=\"" + explicit + "\">" + relative + "</acronym>");
  } else {
    document.write(explicit);
  }
}

function relativeDate(dateString) {
  var now = new Date();
  var hours = now.getHours();
  var minutes = now.getMinutes();
  var reference = new Date(dateString);
  if (isNaN(reference)) return dateString;
  // Calculate time offset between the two dates
  var offset = reference.getTime() - now.getTime();



  // TIME AGO
  //MINUTES
  if ((offset > TWOMINUTESAGO) && (offset <= ONEMINUTEAGO)) return "1 Minute Ago";
  if ((offset > THREEMINUTESAGO) && (offset <= TWOMINUTESAGO)) return "2 MinuteS Ago";
  if ((offset > FOURMINUTESAGO) && (offset <= THREEMINUTESAGO)) return "3 Minute Ago";
  if ((offset > FIVEMINUTESAGO) && (offset <= FOURMINUTESAGO)) return "4 Minutes Ago";
  if ((offset > SIXMINUTESAGO) && (offset <= FIVEMINUTESAGO)) return "5 Minutes Ago";
  if ((offset > SEVENMINUTESAGO) && (offset <= SIXMINUTESAGO)) return "6 Minutes Ago";
  if ((offset > EIGHTMINUTESAGO) && (offset <= SEVENMINUTESAGO)) return "7 Minutes Ago";
  if ((offset > NINEMINUTESAGO) && (offset <= EIGHTMINUTESAGO)) return "8 Minutes Ago";
  if ((offset > TENMINUTESAGO) && (offset <= NINEMINUTESAGO)) return "9 Minutes Ago";
  if ((offset > ELEVENMINUTESAGO) && (offset <= TENMINUTESAGO)) return "10 Minutes Ago";
  if ((offset > TWELVEMINUTESAGO) && (offset <= ELEVENMINUTESAGO)) return "11 Minutes Ago";
  if ((offset > THIRTEENMINUTESAGO) && (offset <= TWELVEMINUTESAGO)) return "12 Minutes Ago";
  if ((offset > FOURTEENMINUTESAGO) && (offset <= THIRTEENMINUTESAGO)) return "13 Minutes Ago";
  if ((offset > FIFTEENMINUTESAGO) && (offset <= FOURTEENMINUTESAGO)) return "14 Minutes Ago";
  if ((offset > SIXTEENMINUTESAGO) && (offset <= FIFTEENMINUTESAGO)) return "15 Minutes Ago";
  if ((offset > SEVENTEENMINUTESAGO) && (offset <= SIXTEENMINUTESAGO)) return "16 Minutes Ago";
  if ((offset > EIGHTEENMINUTESAGO) && (offset <= SEVENTEENMINUTESAGO)) return "17 Minutes Ago";
  if ((offset > NINETEENMINUTESAGO) && (offset <= EIGHTEENMINUTESAGO)) return "18 Minutes Ago";
  if ((offset > TWENTYMINUTESAGO) && (offset <= NINETEENMINUTESAGO)) return "19 Minutes Ago";
  if ((offset > TWENTYONEMINUTESAGO) && (offset <= TWENTYMINUTESAGO)) return "20 Minutes Ago";
  if ((offset > TWENTYTWOMINUTESAGO) && (offset <= TWENTYONEMINUTESAGO)) return "21 Minutes Ago";
  if ((offset > TWENTYTHREEMINUTESAGO) && (offset <= TWENTYTWOMINUTESAGO)) return "22 Minutes Ago";
  if ((offset > TWENTYFOURMINUTESAGO) && (offset <= TWENTYTHREEMINUTESAGO)) return "23 Minutes Ago";
  if ((offset > TWENTYFIVEMINUTESAGO) && (offset <= TWENTYFOURMINUTESAGO)) return "24 Minutes Ago";
  if ((offset > TWENTYSIXMINUTESAGO) && (offset <= TWENTYFIVEMINUTESAGO)) return "25 Minutes Ago";
  if ((offset > TWENTYSEVENMINUTESAGO) && (offset <= TWENTYSIXMINUTESAGO)) return "26 Minutes Ago";
  if ((offset > TWENTYEIGHTMINUTESAGO) && (offset <= TWENTYSEVENMINUTESAGO)) return "27 Minutes Ago";
  if ((offset > TWENTYNINEMINUTESAGO) && (offset <= TWENTYEIGHTMINUTESAGO)) return "28 Minutes Ago";
  if ((offset > THIRTYMINUTESAGO) && (offset <= TWENTYNINEMINUTESAGO)) return "29 Minutes Ago";
  if ((offset > THIRTYONEMINUTESAGO) && (offset <= THIRTYMINUTESAGO)) return "30 Minutes Ago";
  if ((offset > THIRTYTWOMINUTESAGO) && (offset <= THIRTYONEMINUTESAGO)) return '31 Minutes Ago' ;
  if ((offset > THIRTYTHREEMINUTESAGO) && (offset <= THIRTYTWOMINUTESAGO)) return '32 Minutes Ago' ;
  if ((offset > THIRTYFOURMINUTESAGO) && (offset <= THIRTYTHREEMINUTESAGO)) return '33 Minutes Ago' ;
  if ((offset > THIRTYFIVEMINUTESAGO) && (offset <= THIRTYFOURMINUTESAGO)) return '34 Minutes Ago' ;
  if ((offset > THIRTYSIXMINUTESAGO) && (offset <= THIRTYFIVEMINUTESAGO)) return '35 Minutes Ago' ;
  if ((offset > THIRTYSEVENMINUTESAGO) && (offset <= THIRTYSIXMINUTESAGO)) return '36 Minutes Ago ';
  if ((offset > THIRTYEIGHTMINUTESAGO) && (offset <= THIRTYSEVENMINUTESAGO)) return '37 Minutes Ago ';
  if ((offset > THIRTYNINEMINUTESAGO) && (offset <= THIRTYEIGHTMINUTESAGO)) return '38 Minutes Ago ';
  if ((offset > FOURTYMINUTESAGO) && (offset <= THIRTYNINEMINUTESAGO)) return '39 Minutes Ago ';
  if ((offset > FOURTYONEMINUTESAGO) && (offset <= FOURTYMINUTESAGO)) return '40 Minutes Ago ';
  if ((offset > FOURTYTWOMINUTESAGO) && (offset <= FOURTYONEMINUTESAGO)) return '41 Minutes Ago ';
  if ((offset > FOURTYTHREEMINUTESAGO) && (offset <= FOURTYTWOMINUTESAGO)) return '42 Minutes Ago' ;
  if ((offset > FOURTYFOURMINUTESAGO) && (offset <= FOURTYTHREEMINUTESAGO)) return '43 Minutes Ago';
  if ((offset > FOURTYFIVEMINUTESAGO) && (offset <= FOURTYFOURMINUTESAGO)) return '44 Minutes Ago ';
  if ((offset > FOURTYSIXMINUTESAGO) && (offset <= FOURTYFIVEMINUTESAGO)) return '45 Minutes Ago' ;
  if ((offset > FOURTYSEVENMINUTESAGO) && (offset <= FOURTYSIXMINUTESAGO)) return '46 Minutes Ago' ;
  if ((offset > FOURTYEIGHTMINUTESAGO) && (offset <= FOURTYSEVENMINUTESAGO)) return '47 Minutes Ago ';
  if ((offset > FOURTYNINEMINUTESAGO) && (offset <= FOURTYEIGHTMINUTESAGO)) return '48 Minutes Ago ';
  if ((offset > FIFTYMINUTESAGO) && (offset <= FOURTYNINEMINUTESAGO)) return '49 Minutes Ago';
  if ((offset > FIFTYONEMINUTESAGO) && (offset <= FIFTYMINUTESAGO)) return '50 Minutes Ago' ;
  if ((offset > FIFTYTWOMINUTESAGO) && (offset <= FIFTYONEMINUTESAGO)) return '51 Minutes Ago ' ;
  if ((offset > FIFTYTHREEMINUTESAGO) && (offset <= FIFTYTWOMINUTESAGO)) return '52 Minutes Ago' ;
  if ((offset > FIFTYFOURMINUTESAGO) && (offset <= FIFTYTHREEMINUTESAGO)) return '53 Minutes Ago ';
  if ((offset > FIFTYFIVEMINUTESAGO) && (offset <= FIFTYFOURMINUTESAGO)) return '54 Minutes Ago ';
  if ((offset > FIFTYSIXMINUTESAGO) && (offset <= FIFTYFIVEMINUTESAGO)) return '55 Minutes Ago ' ;
  if ((offset > FIFTYSEVENMINUTESAGO) && (offset <= FIFTYSIXMINUTESAGO)) return '56 Minutes Ago ';
  if ((offset > FIFTYEIGHTMINUTESAGO) && (offset <= FIFTYSEVENMINUTESAGO)) return '57 Minutes Ago';
  if ((offset > FIFTYNINEMINUTESAGO) && (offset <= FIFTYEIGHTMINUTESAGO)) return '58 Minutes Ago ';
  if ((offset > SIXTYMINUTESAGO) && (offset <= FIFTYNINEMINUTESAGO)) return '59 Minutes Ago';
   //HOURS
  if ((offset > TWOHOURSAGO) && (offset <= ONEHOURAGO))
  {
      var minsOffset = Math.round(Math.abs(offset / 60000 + 60));
      return ('One hour and '+ minsOffset + ' Minutes ago.');
  }
  if ((offset > THREEHOURSAGO) && (offset <= TWOHOURSAGO))
   {
      var minsOffset = Math.round(Math.abs(offset / 60000 + 60));
      return ('Two hours and '+ minsOffset + ' Minutes ago.');
  }
  if ((offset > FOURHOURSAGO) && (offset <= THREEHOURSAGO))
  {
      var minsOffset = Math.round(Math.abs(offset / 60000 + 60));
      return ('Three hours and '+ minsOffset + ' Minutes ago.');
  }
  if ((offset > FIVEHOURSAGO) && (offset <= FOURHOURSAGO))
   {
      var minsOffset = Math.round(Math.abs(offset / 60000 + 60));
      return ('Four hours and '+ minsOffset + ' Minutes ago.');
  }
  if ((offset > SIXHOURSAGO) && (offset <= FIVEHOURSAGO))
   {
      var minsOffset = Math.round(Math.abs(offset / 60000 + 60));
      return ('Five hours and '+ minsOffset + ' Minutes ago.');
  }
  if ((offset > SEVENHOURSAGO) && (offset <= SIXHOURSAGO))
   {
      var minsOffset = Math.round(Math.abs(offset / 60000 + 60));
      return ('Six hours and '+ minsOffset + ' Minutes ago.');
  }
  if ((offset > EIGHTHOURSAGO) && (offset <= SEVENHOURSAGO))
   {
      var minsOffset = Math.round(Math.abs(offset / 60000 + 60));
      return ('Seven hours and '+ minsOffset + ' Minutes ago.');
  }
  if ((offset > NINEHOURSAGO) && (offset <= EIGHTHOURSAGO))
   {
      var minsOffset = Math.round(Math.abs(offset / 60000 + 60));
      return ('Eight hours and '+ minsOffset + ' Minutes ago.');
  }
  if ((offset > TENHOURSAGO) && (offset <= NINEHOURSAGO))
   {
      var minsOffset = Math.round(Math.abs(offset / 60000 + 60));
      return ('Nine hours and '+ minsOffset + ' Minutes ago.');
  }
  if ((offset > ELEVENHOURSAGO) && (offset <= TENHOURSAGO))
   {
      var minsOffset = Math.round(Math.abs(offset / 60000 + 60));
      return ('Ten hours and '+ minsOffset + ' Minutes ago.');
  }
  if ((offset > TWELVEHOURSAGO) && (offset <= ELEVENHOURSAGO))
   {
      var minsOffset = Math.round(Math.abs(offset / 60000 + 60));
      return ('Eleven hours and '+ minsOffset + ' Minutes ago.');
  }
  if ((offset > THIRTEENHOURSAGO) && (offset <= TWELVEHOURSAGO)) return 'today at: '+reference;
 
 
  if ((offset > FOURTEENHOURSAGO) && (offset <= THIRTEENHOURSAGO)) return 'today at:' + reference ;
  if ((offset > FIFTEENHOURSAGO) && (offset <= FOURTEENHOURSAGO)) return 'today at:' + reference ;
  if ((offset > SIXTEENHOURSAGO) && (offset <= FIFTEENHOURSAGO)) return 'today at:' + reference ;
  if ((offset > SEVENTEENHOURSAGO) && (offset <= SIXTEENHOURSAGO)) return 'today at:' + reference ;
  if ((offset > EIGHTEENHOURSAGO) && (offset <= SEVENTEENHOURSAGO)) return 'today at:' + reference ;
  if ((offset > NINETEENHOURSAGO) && (offset <= EIGHTEENHOURSAGO)) return 'today at:' + reference ;
  if ((offset > TWENTYHOURSAGO) && (offset <= NINETEENHOURSAGO)) return 'today at:' + reference ;
  if ((offset > TWENTYONEHOURSAGO) && (offset <= TWENTYHOURSAGO)) return 'today at:' + reference ;
  if ((offset > TWENTYTWOHOURSAGO) && (offset <= TWENTYONEHOURSAGO)) return 'today at:' + reference ;
  if ((offset > TWENTYTHREEHOURSAGO) && (offset <= TWENTYTWOHOURSAGO)) return 'today at:' + reference ;
  if ((offset > TWENTYFOURHOURSAGO) && (offset <= TWENTYTHREEHOURSAGO)) return 'today at:' + reference ;


  //Days
  if ((offset > TWODAYSAGO) && (offset <= ONEDAYAGO)) return "1 Day Ago";
  if ((offset > THREEDAYSAGO) && (offset <= TWODAYSAGO)) return "2 Days Ago";
  if ((offset > FOURDAYSAGO) && (offset <=THREEDAYSAGO)) return "3 Days Ago";


   // None of the above
  return explicitDate(dateString, false);
}

function explicitDate(dateString, includeYearRegardless) {
  var now = new Date();
  var reference = new Date(dateString);
  if (isNaN(reference)) return dateString;
  var date = reference.getDate();
  var month = monthAbbreviations[reference.getMonth()];
  var hours = reference.getHours();
  var minutes = reference.getMinutes();
  var seconds = reference.getSeconds();
  var year = reference.getFullYear();
  // Only show the year if out of current year!!!!
 /* if ((reference.getFullYear() != now.getFullYear()) || includeYearRegardless) {
    var year = ", " + reference.getFullYear();
  } else {
    var year = "";
  }*/
  return(month + date + ', ' + year + ' at ' + hours +':'+ minutes);
}

thanks!

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2006-08-17 at 02:47:23ID21957646
Tags

javascript

,

file

,

js

Topic

JavaScript

Participating Experts
2
Points
500
Comments
5

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. is there a function similar to a dateadd() in JS?
    first and fore most I will add more points to this question once my account gets reset thanks.. I was wondering if there is such a thing as a dateAdd() function like in sql or Coldfusion but in Js. I have been trying to code something rather complicated for a while no...
  2. Modem can only dial nine digits!
    I have a LT Win modem on a Toshiba laptop which works fine except it can't dial out if the number is over nine digits. ATDT x dials OK if x is at most nine digits, and it returns ERROR if x is ten digits or more. Can someone help me?
  3. cut-through
    This is from CCNA: Cisco Certified Network Associate Exam Notes, Third Edition ISBN: 0782141684 by Todd Lammle and Sean Odom : "Using the cut-through switching method, the LAN switch copies only the destination address that is contained in the first 14 bytes of the...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: mplungjanPosted on 2006-08-17 at 04:44:49ID: 17333178

It should look something like this - not fully tested so please look at the math - there is an issue around 12 hours
<script>
var monthAbbreviations = "January,February,March,April,May,June,July,August,September,October,November,December".split(',');
var daysOfTheWeek = "Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday".split(',');
var timeString = "ZERO,ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE,TEN,"+
"ELEVEN,TWELVE,THIRTEEN,FOURTEEN,FIFTEEN,SIXTEEN,SEVENTEEN,EIGHTEEN,NINETEEN,TWENTY,"+
"TWENTYONE,TWENTYTWO,TWENTYTHREE,TWENTYFOUR,TWENTYFIVE,TWENTYSIX,TWENTYSEVEN,TWENTYEIGHT,TWENTYNINE,THIRTY,"+
"THIRTYONE,THIRTYTWO,THIRTYTHREE,THIRTYFOUR,THIRTYFIVE,THIRTYSIX,THIRTYSEVEN,THIRTYEIGHT,THIRTYNINE,FOURTY,"+
"FOURTYONE,FOURTYTWO,FOURTYTHREE,FOURTYFOUR,FOURTYFIVE,FOURTYSIX,FOURTYSEVEN,FOURTYEIGHT,FOURTYNINE,"+
"FIFTY,FIFTYONE,FIFTYTWO,FIFTYTHREE,FIFTYFOUR,FIFTYFIVE,FIFTYSIX,FIFTYSEVEN,FIFTYEIGHT,FIFTYNINE,SIXTY"
var timeAsText = timeString.split(',');

function dateReference(dateString) {
  var relative = relativeDate(dateString);
  alert(relative)
  var explicit = explicitDate(dateString, true);
  alert(explicit)
  if (relative != explicit) {
    document.write("&lt;acronym title=\"" + explicit + "\">" + relative + "&lt;/acronym>");
  } else {
    document.write(explicit);
  }
}
var aSecond = 1000;
var aMinute = 60*aSecond;
var anHour = 60*aMinute;
var aDay = 24*anHour;
function relativeDate(dateString) {
  var now = new Date();
  var hours = now.getHours();
  var minutes = now.getMinutes();
  var reference = new Date(dateString);
  if (isNaN(reference)) return dateString;
  // Calculate time offset between the two dates
  var offset = Math.abs(reference.getTime() - now.getTime());
  var offsetInDays = Math.round(offset/(24*anHour));
  var showDays = offsetInDays > 0;
  offset -= offsetInDays*aDay
  var offsetInHours = Math.round(offset/anHour);
  var showHours = !showDays && (offsetInHours > 0);
  offset -= offsetInHours*anHour;
  alert(offset)
  var offsetInMinutes = Math.round(offset/aMinute);
  var showMinutes = !showDays && !showHours && (offsetInMinutes >0)
  offset -= offsetInMinutes*aMinute;
  alert(offset)
  var offsetInSeconds = Math.round(offset/aSecond);
 
alert('offset:'+offset+'\nsecs '+offsetInSeconds+'\nmin '+offsetInMinutes+'\nhours '+offsetInHours+'\ndays '+offsetInDays)
  // TIME AGO
  //MINUTES
  if (showMinutes) {
    var plurMin = (offsetInMinutes==1) ? '':'s';
    return timeAsText[offsetInMinutes] +" Minute"+plurMin+" Ago";
  }
     //HOURS
  if (showHours) {
     alert('hours:'+offsetInHours+':'+timeAsText[offsetInHours])
     offsetInMinutes -= (offsetInHours *60);
     if (offsetInHours < 12) return 'today at: '+reference;

     var plurHour = (offsetInHours==1) ? '':'s';
     var plurMin = (offsetInMinutes==1) ? '':'s';
     hourText =  timeAsText[offsetInHours]+' hour'+plurHour;
     minuteText = ' and '+ timeAsText[offsetInMinutes] + ' Minute'+plurMin;
alert( offsetInHours+':'+ timeAsText[offsetInHours]+' ' + offsetInMinutes +':'+timeAsText[offsetInMinutes])
     return (hourText+minuteText+' ago.');
  }
 
  //Days
  if (showDays && offsetInDays < 4) {
    plurDay = (offsetInDays==1) ? '':'s';
    return timeAsText[offsetInDays]+' Day'+plurDay+' Ago';
  }

   // None of the above
  return explicitDate(dateString, false);
}

function explicitDate(dateString, includeYearRegardless) {
  var now = new Date();
  var reference = new Date(dateString);
  if (isNaN(reference)) return dateString;
  var date = reference.getDate();
  var month = monthAbbreviations[reference.getMonth()];
  var hours = reference.getHours();
  var minutes = reference.getMinutes();
  minutes = (minutes < 10)? "0"+minutes:minutes;
  var seconds = reference.getSeconds();
  seconds = (seconds < 10)? "0"+seconds:seconds;
  var year = reference.getFullYear();
  // Only show the year if out of current year!!!!
 /* if ((reference.getFullYear() != now.getFullYear()) || includeYearRegardless) {
    var year = ", " + reference.getFullYear();
  } else {
    var year = "";
  }*/
  return(month + ' ' +date + ', ' + year + ' at ' + hours +':'+ minutes);
}
dateReference("2006/08/17 03:00:00")
</script>

 

by: mplungjanPosted on 2006-08-17 at 05:07:37ID: 17333303

PS: Using a little bit of math the timeAsText can be further reduced

 

by: MrHorizontalPosted on 2006-08-17 at 05:13:08ID: 17333343

I built a JS Object called js_SuperDate which is totally compatible with the standard Date() object, but with extended features, such as complete date-to-string manipulation, plus an offset date function which allows you to do the stuff you were doing, and a very rudimentary date command parser (it's crap, but works). I have been meaning to add DatePart and DateAdd functions, but haven't got round to it...

It is long, but just put it in it's own js file and include it...

Anyway, here you go:

      /*
       * Super date function!!!
        */
      function js_SuperDate()
      {
            if (arguments.length > 0)
                  this.dt = new Date(arguments[0] + '');
            else
                  this.dt = new Date();
      }

// mirror the same interface as the Date() object:
      js_SuperDate.prototype.Months = ['January',      'February', 'March',      'April',      'May',            'June',            'July',      'August', 'September', 'October', 'November', 'December'];
      js_SuperDate.prototype.Days   = ['Sunday',      'Monday',      'Tuesday',      'Wednesday','Thursday', 'Friday',      'Saturday'];
      js_SuperDate.prototype.AMPM   = ['AM',            'PM'];

      js_SuperDate.prototype.getDate = function()
      {
            return this.dt.getDate();
      }

      js_SuperDate.prototype.getDay = function()
      {
            return this.dt.getDay();
      }

      js_SuperDate.prototype.getFullYear = function()
      {
            return this.dt.getFullYear();
      }

      js_SuperDate.prototype.getHours = function()
      {
            return this.dt.getHours();
      }

      js_SuperDate.prototype.getMilliseconds = function()
      {
            return this.dt.getMilliseconds();
      }

      js_SuperDate.prototype.getMinutes = function()
      {
            return this.dt.getMinutes();
      }

      js_SuperDate.prototype.getMonth = function()
      {
            return this.dt.getMonth();
      }

      js_SuperDate.prototype.getSeconds = function()
      {
            return this.dt.getSeconds();
      }

      js_SuperDate.prototype.getTime = function()
      {
            return this.dt.getTime();
      }

      js_SuperDate.prototype.getTimezoneOffset = function()
      {
            return this.dt.getTimezoneOffset();
      }

      js_SuperDate.prototype.getUTCDate = function()
      {
            return this.dt.getUTCDate();
      }

      js_SuperDate.prototype.getUTCDay = function()
      {
            return this.dt.getUTCDay();
      }

      js_SuperDate.prototype.getUTCFullYear = function()
      {
            return this.dt.getUTCFullYear();
      }

      js_SuperDate.prototype.getUTCHours = function()
      {
            return this.dt.getUTCHours();
      }

      js_SuperDate.prototype.getUTCMilliseconds = function()
      {
            return this.dt.getUTCMinutes();
      }

      js_SuperDate.prototype.getUTCMonth = function()
      {
            return this.dt.getUTCMonth();
      }

      js_SuperDate.prototype.getUTCSeconds = function()
      {
            return this.dt.getUTCSeconds();
      }

      js_SuperDate.prototype.getYear = function()
      {
            return this.dt.getYear();
      }

      js_SuperDate.prototype.parse = function(_in)
      {
            return this.dt.parse(_in);
      }

      js_SuperDate.prototype.setDate = function(_in)
      {
            return this.dt.setDate(_in);
      }

      js_SuperDate.prototype.setFullYear = function(_in)
      {
            return this.dt.setFullYear(_in);
      }

      js_SuperDate.prototype.setHours = function(_in)
      {
            return this.dt.setHours(_in);
      }

      js_SuperDate.prototype.setMilliseconds = function(_in)
      {
            return this.dt.setMilliseconds(_in);
      }

      js_SuperDate.prototype.setMinutes = function(_in)
      {
            return this.dt.setMinutes(_in);
      }

      js_SuperDate.prototype.setMonth = function(_in)
      {
            return this.dt.setMonth(_in);
      }

      js_SuperDate.prototype.setSeconds = function(_in)
      {
            return this.dt.setSeconds(_in);
      }

      js_SuperDate.prototype.setTime = function(_in)
      {
            return this.dt.setTime(_in);
      }

      js_SuperDate.prototype.setUTCDate = function(_in)
      {
            return this.dt.setUTCDate(_in);
      }

      js_SuperDate.prototype.setUTCFullYear = function(_in)
      {
            return this.dt.setUTCFullYear(_in);
      }

      js_SuperDate.prototype.setUTCHours = function(_in)
      {
            return this.dt.setUTCHours(_in);
      }

      js_SuperDate.prototype.setUTCMilliseconds = function(_in)
      {
            return this.dt.setUTCMilliseconds(_in);
      }

      js_SuperDate.prototype.setUTCMinutes = function(_in)
      {
            return this.dt.setUTCMinutes(_in);
      }

      js_SuperDate.prototype.setUTCMonth = function(_in)
      {
            return this.dt.setUTCMonth(_in);
      }

      js_SuperDate.prototype.setUTCSeconds = function(_in)
      {
            return this.dt.setUTCSeconds(_in);
      }

      js_SuperDate.prototype.setYear = function(_in)
      {
            return this.dt.setYear(_in);
      }

      js_SuperDate.prototype.toGMTString = function()
      {
            return this.dt.toGMTString();
      }

      js_SuperDate.prototype.toLocaleString = function()
      {
            return this.dt.toLocaleString();
      }

      js_SuperDate.prototype.toString = function()
      {
            return this.dt.toString();
      }

      js_SuperDate.prototype.toUTCString = function()
      {
            return this.dt.toUTCString();
      }

      js_SuperDate.prototype.UTC = function()
      {
            return this.dt.UTC();
      }

      js_SuperDate.prototype.valueOf = function()
      {
            return this.dt.valueOf();
      }

// GMT-named versions of UTC
      js_SuperDate.prototype.getGMTDate = function()
      {
            return this.getUTCDate();
      }

      js_SuperDate.prototype.getGMTDay = function()
      {
            return this.getUTCDay();
      }

      js_SuperDate.prototype.getGMTFullYear = function()
      {
            return this.getUTCFullYear();
      }

      js_SuperDate.prototype.getGMTHours = function()
      {
            return this.getUTCHours();
      }

      js_SuperDate.prototype.getGMTMilliseconds = function()
      {
            return this.getUTCMinutes();
      }

      js_SuperDate.prototype.getGMTMonth = function()
      {
            return this.getUTCMonth();
      }

      js_SuperDate.prototype.getGMTSeconds = function()
      {
            return this.getUTCSeconds();
      }

      js_SuperDate.prototype.setGMTDate = function(_in)
      {
            return this.setUTCDate(_in);
      }

      js_SuperDate.prototype.setGMTFullYear = function(_in)
      {
            return this.setUTCFullYear(_in);
      }

      js_SuperDate.prototype.setGMTHours = function(_in)
      {
            return this.setUTCHours(_in);
      }

      js_SuperDate.prototype.setGMTMilliseconds = function(_in)
      {
            return this.setUTCMilliseconds(_in);
      }

      js_SuperDate.prototype.setGMTMinutes = function(_in)
      {
            return this.setUTCMinutes(_in);
      }

      js_SuperDate.prototype.setGMTMonth = function(_in)
      {
            return this.setUTCMonth(_in);
      }

      js_SuperDate.prototype.setGMTSeconds = function(_in)
      {
            return this.setUTCSeconds(_in);
      }

      js_SuperDate.prototype.GMT = function()
      {
            return this.UTC();
      }

// Strings
      js_SuperDate.prototype.getStrd = function()
      {
            var ret = this.getDate()+'';
            return ret;
      }


      js_SuperDate.prototype.getStrdd = function()
      {
            var ret = this.getDate()+'';
            if (ret.length < 2)
                  ret = '0' + ret;
            return ret;
      }

      js_SuperDate.prototype.getStrM = function()
      {
            var ret = (this.getMonth()+1)+'';
            return ret;
      }

      js_SuperDate.prototype.getStrMM = function()
      {
            var ret = (this.getMonth()+1)+'';
            if (ret.length < 2)
                  ret = '0' + ret;
            return ret;
      }

      js_SuperDate.prototype.getStrMMM = function()
      {
            return this.Months[this.getMonth()].substring(0,3)+'';
      }

      js_SuperDate.prototype.getStrMMMM = function()
      {
            return this.Months[this.getMonth()]+'';
      }

      js_SuperDate.prototype.getStrmmm = function()
      {
            return this.getStrMMM();
      }

      js_SuperDate.prototype.getStrmmmm = function()
      {
            return this.getStrMMMM();
      }

      js_SuperDate.prototype.getStrD = function()
      {
            return this.Days[this.getDay()].substring(0,1)+'';
      }

      js_SuperDate.prototype.getStrDD = function()
      {
            return this.Days[this.getDay()].substring(0,2)+'';
      }

      js_SuperDate.prototype.getStrDDD = function()
      {
            return this.Days[this.getDay()].substring(0,3)+'';
      }

      js_SuperDate.prototype.getStrDDDD = function()
      {
            return this.Days[this.getDay()]+'';
      }

      js_SuperDate.prototype.getStrY = function()
      {
            return (this.getFullYear()+'').substring(3,4)+'';
      }

      js_SuperDate.prototype.getStrYY = function()
      {
            return (this.getFullYear()+'').substring(2,4)+'';
      }

      js_SuperDate.prototype.getStrYYYY = function()
      {
            return this.getFullYear()+'';
      }

      js_SuperDate.prototype.getStry = function()
      {
            return this.getStrY();
      }

      js_SuperDate.prototype.getStryy = function()
      {
            return this.getStrYY();
      }

      js_SuperDate.prototype.getStryyyy = function()
      {
            return this.getStrYYYY();
      }

      js_SuperDate.prototype.getStrH = function()
      {
            var ret = this.getHours()+'';
            return ret;
      }

      js_SuperDate.prototype.getStrHH = function()
      {
            var ret = this.getHours()+'';
            if (ret.length < 2)
                  ret = '0' + ret;
            return ret;
      }

      js_SuperDate.prototype.getStrh = function()
      {
            var ret = '';
            if (this.getHours() < 13)
                  ret = this.getHours()+'';
            else
                  ret = (this.getHours() - 12) +'';
            return ret;
      }

      js_SuperDate.prototype.getStrhh = function()
      {
            var ret = '';;
            if (this.getHours() < 13)
                  ret = this.getHours()+'';
            else
                  ret = (this.getHours() - 12)+'';
            if (ret.length < 2)
                  ret = '0' + ret;
            return ret;
      }

      js_SuperDate.prototype.getStrm = function()
      {
            var ret = this.getMinutes()+'';
            return ret;
      }

      js_SuperDate.prototype.getStrmm = function()
      {
            var ret = this.getMinutes()+'';
            if (ret.length < 2)
                  ret = '0' + ret;
            return ret;
      }

      js_SuperDate.prototype.getStrS = function()
      {
            var ret = this.getSeconds()+'';
            return ret;
      }

      js_SuperDate.prototype.getStrSS = function()
      {
            var ret = this.getSeconds()+'';
            if (ret.length < 2)
                  ret = '0' + ret;
            return ret;
      }

      js_SuperDate.prototype.getStrs = function()
      {
            return this.getStrS();
      }

      js_SuperDate.prototype.getStrss = function()
      {
            return this.getStrSS();
      }

      js_SuperDate.prototype.getStr000 = function()
      {
            var ret = this.getMilliseconds()+'';
            if (ret.length < 3)
                  ret = '0' + ret;
            else if (ret.length < 2)
                  ret = '00' + ret;
            return ret;
      }

      js_SuperDate.prototype.getStr0 = function()
      {
            return this.getMilliseconds()+'';
      }

      js_SuperDate.prototype.getStrTT = function()
      {
            var ret = '';;
            if (this.getHours() < 13)
                  ret = this.AMPM[0].toUpperCase()+'';
            else
                  ret = this.AMPM[1].toUpperCase()+'';
            return ret;
      }

      js_SuperDate.prototype.getStrtt = function()
      {
            var ret = '';;
            if (this.getHours() < 13)
                  ret = this.AMPM[0].toLowerCase()+'';
            else
                  ret = this.AMPM[1].toLowerCase()+'';
            return ret;
      }


// Date Command Parser
      js_SuperDate.prototype.getDateString = function(_cmd)
      {
            var delim = ' ';
            if (arguments.length > 1)
                  delim = arguments[1];
            var illegalChars = [' ','!','"','£','$','%','^','&','*','(',')','-','_','=','+','{','}','[',']',';',':','@',"'",'~','#','<','>',',','.','/','?','\\','|']
            var cmd = _cmd + '';
            var cmd_clean = '';
            for (i = 0; i < cmd.length; ++i)
            {
                  var charOK = true;
                  var tChar  = cmd.charAt(i);
                  for (j = 0; j < illegalChars.length; ++j)
                  {
                        if (tChar == illegalChars[j] && tChar != delim)
                              charOK = false;
                  }
                  if (charOK)
                        cmd_clean += tChar;
            }
            var cmds = cmd_clean.split(delim);
            var legalEntities = ['d','dd','D','DD','DDD','DDDD','m','mm','M','MM','MMM','MMMM','Y','YY','YYYY','y','yy','yyyy','H','HH','h','hh','S','SS','s','ss','TT','tt','0','000']
            var ret = '';
            for (i = 0; i < cmds.length; ++i)
            {
                  var cmdOK = false
                  for (j = 0; j < legalEntities.length; j++)
                  {
                        if (cmds[i] == legalEntities[j])
                              cmdOK = true;
                  }
                  if (cmdOK)
                  {
                        if (i > 0)
                              ret += delim;
                        ret += eval('this.getStr' + cmds[i] + '()');
                  }
            }
            return ret;
      }

// DB-usable date string
      js_SuperDate.prototype.getDBDate = function()
      {
            // dd-MMM-yyyy
            return this.getStrdd() + '-' + this.getStrMMM() + '-' + this.getFullYear();
      }

      js_SuperDate.prototype.getShortDate = function()
      {
            // dd-MMM-yyyy
            return this.getStrd() + ' ' + this.getStrMMM() + ' ' + this.getFullYear();
      }

// RFC-1123 dateformat
      js_SuperDate.prototype.getRFC1123Date = function()
      {
            // dd-MMM-yyyy
            return this.getStrMMM() + ' ' + this.getStrdd() + ', ' + this.getFullYear() + ' ' + this.getStrHH() + ':' + this.getStrmm() + ':' + this.getStrSS();
      }


      var now = new js_SuperDate();

      function js_OffsetDate(_period,_timeunit)
      {
            var td = new js_SuperDate();
            var n = td.getTime();
            switch(_timeunit)
            {
                  case 'Y' :
                        // year
                        td.setTime(n + (_period * 31557600000));
                        break;
                  case 'M' :
                        // month
                        td.setTime(n + (_period * 2629800000));
                        break;
                  case 'd' :
                        // day
                        td.setTime(n + (_period * 86400000));
                        break;
                  case 'D' :
                        // day
                        td.setTime(n + (_period * 86400000));
                        break;
                  case 'H' :
                        // hour
                        td.setTime(n + (_period * 3600000));
                        break;
                  case 'm' :
                        // minute
                        td.setTime(n + (_period * 60000));
                        break;
                  case 'S' :
                        // seconds
                        td.setTime(n + (_period * 1000));
                        break;
                  case '0' :
                        // milliseconds
                        td.setTime(n + _period);
                        break;
            }
            return td.toGMTString();
      }

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...