[javascript] Convert string to datetime

How to convert string like '01-01-1970 00:03:44' to datetime?

This question is related to javascript string date datetime type-conversion

The answer is


By using Date.parse() you get the unix timestamp.

date = new Date( Date.parse("05/01/2020") )
//Fri May 01 2020 00:00:00 GMT

Shouldn't this also work for Rails?

"30/Nov/2009 16:29:30 +0100".to_datetime

I used Time.parse("02/07/1988"), like some of the other posters.

An interesting gotcha was that Time was loaded by default when I opened up IRB, but Time.parse was not defined. I had to require 'time' to get it to work.

That's with Ruby 2.2.


in Ruby 1.8, the ParseDate module will convert this and many other date/time formats. However, it does not deal gracefully with the colon between the year and the hour. Assuming that colon is a typo and is actually a space, then:

#!/usr/bin/ruby1.8

require 'parsedate'

s = "30/Nov/2009 16:29:30 +0100"
p Time.mktime(*ParseDate.parsedate(s))    # =>  Mon Nov 30 16:29:30 -0700 2009

well, thought I should mention a solution I came across through some trying. Discovered whilst fixing a defect of someone comparing dates as strings.

new Date(Date.parse('01-01-1970 01:03:44'))


You could use the moment.js library.

Then simply:

var stringDate = '01-01-1970 00:03:44';
var momentDateObj = moment(stringDate);

Checkout their api also, helps with formatting, adding, subtracting (days, months, years, other moment objects).

I hope this helps.

Rhys


DateTime.strptime allows you to specify the format and convert a String to a DateTime.


I have had success with:

require 'time'
t = Time.parse(some_string)

Keep it simple with new Date(string). This should do it...

const s = '01-01-1970 00:03:44';
const d = new Date(s);
console.log(d); // ---> Thu Jan 01 1970 00:03:44 GMT-0500 (Eastern Standard Time)

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date


EDIT: "Code Different" left a valuable comment that MDN no longer recommends using Date as a constructor like this due to browser differences. While the code above works fine in Chrome (v87.0.x) and Edge (v87.0.x), it gives an "Invalid Date" error in Firefox (v84.0.2).

One way to work around this is to make sure your string is in the more universal format of YYYY-MM-DD (obligatory xkcd), e.g., const s = '1970-01-01 00:03:44';, which seems to work in the three major browsers, but this doesn't exactly answer the original question.


For chinese Rails developers:

DateTime.strptime('2012-12-09 00:01:36', '%Y-%m-%d %H:%M:%S')
=> Sun, 09 Dec 2012 00:01:36 +0000

This will convert the string in date to datetime, if using Rails:

"05/05/2012".to_time

Doc Reference: https://apidock.com/rails/String/to_time


formatDateTime(sDate,FormatType) {
    var lDate = new Date(sDate)

    var month=new Array(12);
    month[0]="January";
    month[1]="February";
    month[2]="March";
    month[3]="April";
    month[4]="May";
    month[5]="June";
    month[6]="July";
    month[7]="August";
    month[8]="September";
    month[9]="October";
    month[10]="November";
    month[11]="December";

    var weekday=new Array(7);
    weekday[0]="Sunday";
    weekday[1]="Monday";
    weekday[2]="Tuesday";
    weekday[3]="Wednesday";
    weekday[4]="Thursday";
    weekday[5]="Friday";
    weekday[6]="Saturday";

    var hh = lDate.getHours() < 10 ? '0' + 
        lDate.getHours() : lDate.getHours();
    var mi = lDate.getMinutes() < 10 ? '0' + 
        lDate.getMinutes() : lDate.getMinutes();
    var ss = lDate.getSeconds() < 10 ? '0' + 
        lDate.getSeconds() : lDate.getSeconds();

    var d = lDate.getDate();
    var dd = d < 10 ? '0' + d : d;
    var yyyy = lDate.getFullYear();
    var mon = eval(lDate.getMonth()+1);
    var mm = (mon<10?'0'+mon:mon);
    var monthName=month[lDate.getMonth()];
    var weekdayName=weekday[lDate.getDay()];

    if(FormatType==1) {
       return mm+'/'+dd+'/'+yyyy+' '+hh+':'+mi;
    } else if(FormatType==2) {
       return weekdayName+', '+monthName+' '+ 
            dd +', ' + yyyy;
    } else if(FormatType==3) {
       return mm+'/'+dd+'/'+yyyy; 
    } else if(FormatType==4) {
       var dd1 = lDate.getDate();    
       return dd1+'-'+Left(monthName,3)+'-'+yyyy;    
    } else if(FormatType==5) {
        return mm+'/'+dd+'/'+yyyy+' '+hh+':'+mi+':'+ss;
    } else if(FormatType == 6) {
        return mon + '/' + d + '/' + yyyy + ' ' + 
            hh + ':' + mi + ':' + ss;
    } else if(FormatType == 7) {
        return  dd + '-' + monthName.substring(0,3) + 
            '-' + yyyy + ' ' + hh + ':' + mi + ':' + ss;
    }
}

You can parse a date time string with a given timezone as well:

zone = "Pacific Time (US & Canada)"
ActiveSupport::TimeZone[zone].parse("2020-05-24 18:45:00")
=> Sun, 24 May 2020 18:45:00 PDT -07:00

https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

var unixTimeZero = Date.parse('01 Jan 1970 00:00:00 GMT');
var javaScriptRelease = Date.parse('04 Dec 1995 00:12:00 GMT');

console.log(unixTimeZero);
// expected output: 0

console.log(javaScriptRelease);
// expected output: 818035920000

For this format (supposed datepart has the format dd-mm-yyyy) in plain javascript:

_x000D_
_x000D_
var dt  = '01-01-1970 00:03:44'.split(/\-|\s/)_x000D_
    dat = new Date(dt.slice(0,3).reverse().join('/')+' '+dt[3]);
_x000D_
_x000D_
_x000D_


http://www.w3schools.com/jsref/jsref_parse.asp

    <script type="text/javascript">
        var d = Date.parse("Jul 8, 2005");
        document.write(d);<br>
    </script>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to type-conversion

How can I convert a char to int in Java? pandas dataframe convert column type to string or categorical How to convert an Object {} to an Array [] of key-value pairs in JavaScript convert string to number node.js Ruby: How to convert a string to boolean Convert bytes to int? Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe SQL Server: Error converting data type nvarchar to numeric How do I convert a Python 3 byte-string variable into a regular string? Leading zeros for Int in Swift