Javascript Date toString convert and format to local time

后端 未结 3 2014
囚心锁ツ
囚心锁ツ 2021-01-28 02:37

I have a script that gets a date/time in the the format of:

2017-06-15 21:00

and then converts it to local time and displays as:



        
相关标签:
3条回答
  • 2021-01-28 02:51

    You'd have to parse it yourself. There are libraries that can do it as well (Stack Overflow rules advise not making recommendations, but if you Google "javascript date format library" a bit you'll find them), but if you want to do it with plain JavaScript, you'll just need to build the string yourself.

    Since you're already creating a Date object, you're half way there.

    The Date object only has numbers, so it won't have strings for things like Thu, Jun and Eastern Daylight Time. For those, you'll need lists of possible values and to map the numbers to them (usually a simple array will work).

    For the 5:00:00 PM part, you can mod (%) the hours by 12, and then specify AM if hours < 12 or PM if hours >= 12.

    const time = (d.getHours() % 12) + ':' + d.getMinutes() + ':' + d.getSeconds() + (d.getHours() < 12 ? 'AM' : 'PM');
    

    I won't give you the full JavaScript because you should take a stab at writing it yourself. If you have any trouble, please ask another question.

    You can also use combinations of toLocaleString(), but it won't do everything you need (it doesn't do 12-hour date format, for example).

    0 讨论(0)
  • 2021-01-28 02:52

    If you can use an external library, I'd suggest this one liner using momentjs:

    moment('2017-06-15 21:00').format('ffffd MMM DD YYYY h:mm:ss A')
    // => "Thu Jun 15 2017 9:00:00 PM"
    
    0 讨论(0)
  • 2021-01-28 03:01

    Using @James suggestion to use toLocaleString()

    $(document).ready(function() {
        $('.plg-date > .fabrikElement > div').each(function() {
            if($(this).text().length > 0) {
                var date = $(this).text();
                var newdate = new Date(date + " UTC");
                var options = { 
                    year: 'numeric', 
                    month: 'numeric', 
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit',
                    timeZoneName: 'short'
                }
                $(this).text(newdate.toLocaleString('en-US', options)); 
            }
        })
    })
    
    0 讨论(0)
提交回复
热议问题