javascript implementation of the detailed time reminder information effect method

  • 2020-05-12 02:14:38
  • OfStack

This article illustrates an example of how javascript implements the effect of a detailed time reminder message. Share with you for your reference. The details are as follows:

We often see personalized time cues on social networks like what your friend updated a few minutes ago, what your friend updated a few days ago.
These little tips are much more human than just showing a certain year and a certain month. We can use different programs to achieve this effect.
This can reduce the pressure on the backend server.

The implementation code of javascript is as follows:

//  This function realizes the more humanized time prompt  
// @param date_str The time passed, time format such as :2010-12-14 18:36:09
function date_parser_diff_return(date_str){
    var  date=new Date();
    if(typeof(date_str)!='string')return date;
    var date_arr=date_str.split(new RegExp("[:| |-]","ig"));
    var date_obj = new Date(date_arr[0],date_arr[1]-1,date_arr[2],date_arr[3],date_arr[4],date_arr[5]);
    var date_seconddiff=( new Date().getTime()-date_obj.getTime() ) /1000 ;
        date_str_w='';
        if(date_seconddiff <60*30)date_str_w= Math.ceil(date_seconddiff/60)+" Minutes ago ";
        if(!date_str_w && date_seconddiff <3600)date_str_w= "1 Hours before ";
        if(!date_str_w && date_seconddiff <3600*2)date_str_w= "2 Hours before ";
        if(!date_str_w && date_seconddiff <3600*3)date_str_w= "3 Hours before ";
        if(!date_str_w && date.getFullYear()==date_arr[0] && date.getMonth()==date_arr[1]-1 && date.getDate()==date_arr[2])
                date_str_w= " Today, "+date_arr[3]+':'+date_arr[4];
        if(!date_str_w && date.getFullYear()==date_arr[0] && date.getMonth()==date_arr[1]-1 && date.getDate()-1==date_arr[2])
                date_str_w= " Yesterday, "+date_arr[3]+':'+date_arr[4];
        if(!date_str_w && date.getFullYear()==date_arr[0] && date.getMonth()==date_arr[1]-1 && date.getDate()-2==date_arr[2])
                date_str_w= " The day before yesterday "+date_arr[3]+':'+date_arr[4];
        if(!date_str_w && date.getFullYear()==date_arr[0] && date.getMonth()==date_arr[1]-1 )
                date_str_w= (date.getMonth()+1)+" month "+  date_arr[2]+" No. "+date_arr[3]+':'+date_arr[4];
        if(!date_str_w && date.getFullYear()==date_arr[0])
               date_str_w= " This year, " + date_arr[1]+" month "+  date_arr[2]+" No. "+date_arr[3]+':'+date_arr[4];
        if(!date_str_w && date.getFullYear()-1==date_arr[0])
               date_str_w= " Last year, " + date_arr[1]+" month "+  date_arr[2]+" No. "+date_arr[3]+':'+date_arr[4];
        document.write(date_str_w);
};

I hope this article is helpful for you to design javascript program.


Related articles: