1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Working with Dates in JS

Discussion in 'Programming' started by Web_Dev_Chris, Nov 1, 2019.

  1. #1
    Hello,

    In MS Excel it is very easy to manipulates dates with formulas. For example I can place a date in a cell. 30-Oct-19 and if I want to work out what 3 days from that day is, I could do 30-Oct-19+3 and it would calculate it.

    How do we do this in JavaScript? I understand we can assign a date to a variable with the date object / create a new instance of the date object and by using date methods we can very easily format 30-Oct-19 and I would like to output 30-Oct-19 to a div. Underneath there is another div. I would like to reference to the above one and calculate 2 days from 30-oct-19 and underneath that there is another div that I would like to reference to the above one and have it display 3 days from that date. Let's say for a roster for example?

    What is the best way to achieve this in JavaScript?
     
    Solved! View solution.
    Web_Dev_Chris, Nov 1, 2019 IP
  2. Web_Dev_Chris

    Web_Dev_Chris Well-Known Member

    Messages:
    222
    Likes Received:
    12
    Best Answers:
    1
    Trophy Points:
    105
    #2
    In excel it would look like this,
    a1 = 30-Oct-19
    a2 = a1+3
    a3 = a2+2

    and it would calculate the dates....
     
    Web_Dev_Chris, Nov 1, 2019 IP
  3. Web_Dev_Chris

    Web_Dev_Chris Well-Known Member

    Messages:
    222
    Likes Received:
    12
    Best Answers:
    1
    Trophy Points:
    105
    #3
    Hi Sorry just to clarify I dont need advice on how to select DOM elements and output variables ect...

    I dont needs advice on shortening a date string ect either.

    I'm thinking I'll need 20 date variables.

    For example this is the initial one:
    var one = new Date(2018, 11, 24, 10, 33, 30, 0);
    var two =

    and basically two should reference one, but I want to write something that would calculate it for two days in advance. I could just do one + 2?
     
    Web_Dev_Chris, Nov 1, 2019 IP
  4. Web_Dev_Chris

    Web_Dev_Chris Well-Known Member

    Messages:
    222
    Likes Received:
    12
    Best Answers:
    1
    Trophy Points:
    105
    #4
    I have tested this in the console and it added the value 3 on the end.

    var two = one + 3;
    undefined
    two
    "Mon Dec 24 2018 10:33:30 GMT+1100 (Australian Eastern Daylight Time)3"
     
    Web_Dev_Chris, Nov 1, 2019 IP
  5. mmerlinn

    mmerlinn Prominent Member

    Messages:
    3,197
    Likes Received:
    818
    Best Answers:
    7
    Trophy Points:
    320
    #5
    I am confused. Is 'ect' a variable? If so, how does it apply to your question? If it is not a variable, what is it?
     
    mmerlinn, Nov 1, 2019 IP
  6. Andrii Ozemko

    Andrii Ozemko Member

    Messages:
    79
    Likes Received:
    11
    Best Answers:
    1
    Trophy Points:
    33
    #6
    May be you can use Moment.js (https://momentjs.com/). I had a lot of pain with date/Time in JavaScript before started using this library.
     
    Andrii Ozemko, Nov 2, 2019 IP
  7. #7
    You can do this
    date.setDate(date.getDate() + 3);

    and if it goes beyond the end of the month it will move to the next month. (You may need to clone the date to not lose the last one) However Andrii is right moment.js is a powerful library and allows you to add days/years/seconds without a lot of debugging. The problem comes when you cross Daylight Saving boundaries, leap months/years etc. The different libraries handle the rollovers slightly differently. Moment.js does fairly sane things that you would do as a human changing dates. Otherwise it's possible to add a month and then find your date is a month + 1 day into the next month or similar issues.

    Other benefit of moment.js, is the custom timezone additions. Native Date handles local timezone and UTC fairly well, although it never gives you any details on what timezone you are working in. Moment.js allows you to switch between all time zones which can be very useful if you store UTC times in your database and want to allow your user to set their own timezone (they may have a preference other than their PC's timezone setting). I personally store UTC/epoch times internally, as it makes moving between different database servers with different mysql timezone settings far easier.
     
    Harry H, Nov 2, 2019 IP
  8. Web_Dev_Chris

    Web_Dev_Chris Well-Known Member

    Messages:
    222
    Likes Received:
    12
    Best Answers:
    1
    Trophy Points:
    105
    #8
    I have tried some quick testing in the console and it doesn't seem to be working

    var today = new Date(2019, 10, 2);
    today
    Sat Nov 02 2019 00:00:00 GMT+1100 (Australian Eastern Daylight Time)
    var tomorrow = new Date(today.getDate() + 1);
    tomorrow
    Thu Jan 01 1970 10:00:00 GMT+1000 (Australian Eastern Standard Time)
     
    Web_Dev_Chris, Nov 2, 2019 IP
  9. Harry H

    Harry H Greenhorn

    Messages:
    27
    Likes Received:
    8
    Best Answers:
    2
    Trophy Points:
    23
    #9
    That's because you have supplied the value of getDate to a new Date constructor. The date constructor take an epoch time. If you typed:

    today.setDate(today.getDate() + 1);

    that should set today to tomorrow. To clone a date:

    var clonedDate = new Date(today.getTime());
     
    Harry H, Nov 2, 2019 IP
  10. Harry H

    Harry H Greenhorn

    Messages:
    27
    Likes Received:
    8
    Best Answers:
    2
    Trophy Points:
    23
    #10
    Where I think you've gone wrong is the functions are badly named. You can't use the functions based on their names, you need to read the API. getDate() returns the day of the month. getTime() returns the number of milliseconds since 1970. new Date(x) expects x to be number of milliseconds since 1970, and you sent it the day of the month. So that will be a few milliseconds after 1970. Hence your output when you print it to the screen.
     
    Harry H, Nov 2, 2019 IP
  11. Web_Dev_Chris

    Web_Dev_Chris Well-Known Member

    Messages:
    222
    Likes Received:
    12
    Best Answers:
    1
    Trophy Points:
    105
    #11
    Thank you for your help. I have worked it out! The computer seems to "LOVE" epoch time.

    function dateForecast(numberOfDays){
        return numberOfDays * 8.64e7;
    }
    
    function epochDate(date){
        return date.valueOf();
    }
    
    let setTheDate = '10 November 2019';
    
    let date1 = new Date(setTheDate);
    let date2 = new Date( epochDate(date1) + dateForecast(3) );
    let date3 = new Date( epochDate(date2) + dateForecast(4) );
    
    console.log(date1);
    console.log(date2);
    console.log(date3);
    Code (JavaScript):
     
    Web_Dev_Chris, Nov 5, 2019 IP
  12. Web_Dev_Chris

    Web_Dev_Chris Well-Known Member

    Messages:
    222
    Likes Received:
    12
    Best Answers:
    1
    Trophy Points:
    105
    #12
    Reviewed and simplified code....

    
    //8.64e7 is the scientific notation for one day in milliseconds
    function dateForecast(dateString, numberOfDays){
        return new Date(dateString.valueOf() + 8.64e7 * numberOfDays);
    }
    
    let setTheDate = '10 November 2019';
    
    let date1 = new Date(setTheDate);
    let date2 = dateForecast(date1,3);
    let date3 = dateForecast(date2,4);
    
    console.log(date1);
    console.log(date2);
    console.log(date3);
    Code (JavaScript):
     
    Last edited: Nov 5, 2019
    Web_Dev_Chris, Nov 5, 2019 IP
  13. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #13
    This might be a silly question, but why are you screwing around with introducing the possibility of float bugs instead of just typing 86400000?

    Also you seem to be passing the date object, but trying to treat it as a string... then doing a valueOf for... uhm... yeah, I don't get that either. But then I don't understand why people think let/const are a good thing either, or why they slop dozens of let/var/const into their code. Too many years working in Wirth family languages I guess...

    
    function dateAddDays(date, days) {
    	return new Date(date.getTime() + 86400000 * days);
    }
    
    var
    	startDate = '10 November 2019',
    	date1 = new Date(startDate),
    	date2 = dateAddDays(date1, 3),
    	date3 = dateAddDays(date2, 4);
    
    console.log(date1);
    console.log(date2);
    console.log(date3);
    
    Code (markup):
     
    deathshadow, Nov 6, 2019 IP
  14. Web_Dev_Chris

    Web_Dev_Chris Well-Known Member

    Messages:
    222
    Likes Received:
    12
    Best Answers:
    1
    Trophy Points:
    105
    #14
    Well actually, I honestly googled how many milliseconds were in a day and it came up with scientific notation.

    This is much cleaner. Thanks.

    Isn’t let/const better for memory management?
     
    Web_Dev_Chris, Nov 6, 2019 IP
  15. Harry H

    Harry H Greenhorn

    Messages:
    27
    Likes Received:
    8
    Best Answers:
    2
    Trophy Points:
    23
    #15
    No let/const isn't better for memory management, they're all GC'd at the end of the day. Potentially const could be better but it'd be very specific to the javascript internals if so. Let was introduced to fix scoping issues with javascript, it is generally the better/recommended one to use. It does more of what you'd expect without as many strange edge cases. Const is used to prevent bugs such as where somebody updates the code later and changes a variable, you then go to use that variable in another update you make but you aren't aware that they have made a change to that variable and you get some strange bugs. Sometimes hard to find if their code branch only runs 5% of the time. Const helps prevent bugs by saying this is what this variable holds and it will never change.

    Disclosure: I use var 99% of the time out of habit and coding js too long and being concerned about backwards compatibility. If you have access to the latest js runtime, then let and const are generally preferable.
     
    Harry H, Nov 7, 2019 IP
  16. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #16
    Well that is better than what most people do -- let the program waste time calculating the value by typing in = 60 * 60 * 24 :D

    Should be many many times worse.Long term footprint since they are released less often, more complex use of stacks and heaps making garbage collection more convoluted, the resultant memory fragmentation, and the lack of hoisting emulating forward declaration.

    There's a reason a lot of more efficient languages do forward declaration or hoisting, so local variables or pointers to their data/structures can be stored on the stack and released when a function call exits. JavaScript doesn't do this and instead relies on "garbage collection" to try and keep memory allocation from becoming a total disaster... but that's why making the already painful conventions of how variables work in JS even more complex is a really derpy idea.

    But as I've said many times, LET and CONST with their "every block is a scope" approach reeks of C++ or Java programmers trying to shoe-horn programming models into a language they just don't fit; typically out of "wah wah, I dunz wanna learn hoisting" mated to an utter unwillingness to accept that JavaScript is NOT their favorite pet language.

    Hell, I'm guilty of that myself at times being a Wirth fanboy. I'll start forward declaring everything and pretending "because that's how it should be done". The trick is to take a step back and accept that no, this isn't your favorite language and it's not meant to work that way.

    Something I feel many programmers coming into JavaScript from other languages fail to wrap their heads around. I know it took me a LONG time to stop trying to make JavaScript behave like Ada, Modula, or Pascal... but once I did and I accepted both the limitations and differences, the quality, reliability, speed, and sustainability of my code was transformed.

    In that way I think beginners are more likely to pick up "the right way" quicker than those of us who've been programming for decades. There's no ingrained habits for them to "unlearn". Learning is easy compared to unlearning. See "confirmation bias" and "cognitive dissonance".

    Sadly people unable to separate that "feeling" from logic often end up in charge, bolting things onto a language it doesn't need and that just makes things harder. USUALLY because they don't know enough about the language to determine what's easy in the first place. Again, see all the "frameworks" out there CREATED BY people who aren't qualified to write a single line of the underlying language. jQuery and Bootstrap being the poster children for that.
     
    deathshadow, Nov 7, 2019 IP
  17. Harry H

    Harry H Greenhorn

    Messages:
    27
    Likes Received:
    8
    Best Answers:
    2
    Trophy Points:
    23
    #17
    Variable hoisting is a horrible default setting for a language. We probably shouldn't be bolting things onto a language but we don't have much choice because javascript is the default language of the web and is subject to design decisions made a long time ago. I honestly don't think anybody actually wants their variables hoisted onto the top of the function (otherwise they'd have put them there in the first place), I see no practical use for that, and only potential bugs stemming from that functionality.
     
    Harry H, Nov 8, 2019 IP
  18. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #18
    Like pretty much every programming language I cut my teeth on when I went from hobbyist to actual developer. Just because C goes full Gungan letting you place variable declarations anywhere you damned well want, doesn't make it a good idea.

    But then C is not my favorite programming language. Kernighan can sod right off...

    From an implementation standpoint -- and how computers really works -- its a far superior model. If it inconveniences anyone in terms of writing the language, they either have no business working in JS in the first place, or they have to unlearn bad habits from other languages.

    I've heard people complain about it endlessly the past decade or so, whilst never ONCE having it bite me or cause a problem. The corner cases where it becomes an issue -- to me at least -- seem to stem from bad practices, ignorance, and promotion of same by worse tutorials and references. See the broken, outdated, scammy trash that is W3Schools.

    Though that could just be my having learned and worked with Wirth family languages right our of ASM in the late '70's to early '80s, not even encountering anyone using C for anything until the early '90's. C was the language we pointed at and made fun of for it being used by the "big iron" dinosaurs alongside the painfully cryptic joke of an OS that was Unix. The return of either to the forefront of computing can be laid almost entirely in one man's lap... Linus Torvalds.

    I've got ingrained habits from spending a decade and a half working in Ada, habits that seem to let me write scripting that is faster, easier to maintain, and in most cases many times smaller -- whilst also being clearer, simpler, and easier to write WITHOUT resorting to over-the-top scoping like LET/CONST, uselessly cryptic garbage like arrow functions, and all the other things in JS that seem to exist for the sole purpose of making programming harder.

    Besides, every time I see "let" I feel like I'm looking at 4k "Level 1" ROM BASIC on a Trash-80 Model I.
     
    Last edited: Nov 8, 2019
    deathshadow, Nov 8, 2019 IP