convert string into datetime format in Javascript - javascript

i have a string which, i want to compare with a javascript datetime object.
how to convert string "1/1/1912" into datetime using JavaScript so that i can compare like
if (EDateTime > ('1/1/1912')) {...}

You could do this simply with a split if you can guarantee the date format.
var dateArray = '1/1/1912'.split("/");
new Date(dateArray[2], dateArray[1], dateArray[0]);

var dateArray = '2012-02-17 01:10:59'.split(' ');
var year = dateArray[0].split('-');
var time = dateArray[1].split(':');
var finishDate = new Date(year[0], year[1], year[2], time[0], time[1], time[2])

How about using DateJS library?
It can convert 1/1/1912 to Monday, January 01, 1912 12:00:00 AM easily

Convert your string to timestamp with Date object.
I found something like:
function toTimestamp(year,month,day,hour,minute,second){
var datum = new Date(Date.UTC(year,month-1,day,hour,minute,second));
return datum.getTime()/1000;
}
Year, month and day parts get with regular expressions.

This library may be helpful.

Related

How to convert an ISO 8601 date to '/Date(1525687010053)/' format in javascript?

How can I convert a date value formatted as 9999-12-31T00:00:00Z to /Date(1525687010053)/ format in javascript?
I have this, but it doesn't work:
var datevalue = '9999-12-31T00:00:00Z';
var converteddate = Date.parseDate(datevalue);
I assume that you want to get the timestamp of that date. This can be achieved with the code below
var timestamp = new Date('9999-12-31T00:00:00Z').getTime()
I don't understand your question, but your code is wrong. There is no Date.parseDate() function in javascript, only Date.parse():
var datevalue = '9999-12-31T00:00:00Z';
var converteddate = Date.parse(datevalue);
document.getElementById('result').innerHTML = converteddate;
console.log(converteddate)
<p id="result"></p>
You can do your conversion in just three easy steps :
Convert your ISO 8601 string to a Date object
Use getTime to convert your Date object to a universal time timestamp
Wrap "/Date(" and ")/" around your result
Demo
function convert(iso8601string) {
return "/Date(" + (new Date(iso8601string)).getTime() + ")/";
}
console.log(convert("2011-10-05T14:48:00.000Z"));

Reading the date from textbox as a string and converting it into as Date

I am reading the date from textbox by using javascript and trying to convert it as Date object.But my problem is date is converting as month and month is converting as date when converting the string to date.
Example:
03/12/2014 the value in the textbox
Actual Output:
03 as March,
12 as date (Its wrong)
Expected Output:
03 as date
12 as December (I am expecting)
While converting this string to date by using following snippet
var startTime = document.getElementById("meeting:startTime");
date.js
var stringToDate_startTime=new Date(Date.parse(startTime.value,"dd/mm/yy"));
moment.js
var date1=moment(startTime.value).format('DD-MM-YYYY');
In the above even i have used date.js and moment.js files also.But those also did not solve my problem.Please can anyone help me out to get rid out of this.
Try ...
var from = startTime.value.split("/");
var newDate = newDate(from[2], from[1] - 1, from[0]);
... assuming time included ...
var date_only = startTime.value.split("");
var from = date_only[0].split("/");
var newDate = newDate(from[2], from[1] - 1, from[0]);
I am not aware of an implementation of the Date.parse() method that accepts two arguments. You can view the Mozilla Date.parse() method description here Date.parse() - JavaScript | MDN.
It might be worth looking at the question/answer of this question for some more information: Why does Date.parse give incorrect results?
The next best option would be to split the date using String.split() and to rearrange the date parts
var dateStr = '03/12/2014 23:05';
var newDateStr = null;
var dateParts = dateStr.split('/');
if (dateParts.length == 3) {
var day = dateParts[0];
var month = dateParts[1];
var yearAndTime = dateParts[2];
// Rearrange the month and day and rejoin the date "12/03/2014 23:05"
newDateStr = [ month, day, yearAndTime].join('/');
} else {
throw new Error('Date not in the expected format.');
}
var date = new Date(newDateStr); // JS Engine will parse the string automagically
alert(date);
This isn't the most elegant solution, but hopefully that helps.

from unix timestamp to datetime

I have something like /Date(1370001284000+0200)/ as timestamp. I guess it is a unix date, isn't it? How can I convert this to a date like this: 31.05.2013 13:54:44
I tried THIS converter for 1370001284 and it gives the right date. So it is in seconds.
But I still get the wrong date for:
var substring = unix_timestamp.replace("/Date(", "");
substring = substring.replace("000+0200)/", "");
var date = new Date();
date.setSeconds(substring);
return date;
Note my use of t.format comes from using Moment.js, it is not part of JavaScript's standard Date prototype.
A Unix timestamp is the number of seconds since 1970-01-01 00:00:00 UTC.
The presence of the +0200 means the numeric string is not a Unix timestamp as it contains timezone adjustment information. You need to handle that separately.
If your timestamp string is in milliseconds, then you can use the milliseconds constructor and Moment.js to format the date into a string:
var t = new Date( 1370001284000 );
var formatted = moment(t).format("dd.mm.yyyy hh:MM:ss");
If your timestamp string is in seconds, then use setSeconds:
var t = new Date();
t.setSeconds( 1370001284 );
var formatted = moment(t).format("dd.mm.yyyy hh:MM:ss");
Looks like you might want the ISO format so that you can retain the timezone.
var dateTime = new Date(1370001284000);
dateTime.toISOString(); // Returns "2013-05-31T11:54:44.000Z"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
Without moment.js:
var time_to_show = 1509968436; // unix timestamp in seconds
var t = new Date(time_to_show * 1000);
var formatted = ('0' + t.getHours()).slice(-2) + ':' + ('0' + t.getMinutes()).slice(-2);
document.write(formatted);
The /Date(ms + timezone)/ is a ASP.NET syntax for JSON dates. You might want to use a library like momentjs for parsing such dates. It would come in handy if you need to manipulate or print the dates any time later.
If using react:
import Moment from 'react-moment';
Moment.globalFormat = 'D MMM YYYY';
then:
<td><Moment unix>{1370001284}</Moment></td>
Import moment js:
var fulldate = new Date(1370001284000);
var converted_date = moment(fulldate).format(");
if you're using React I found 'react-moment' library more easy to handle for Front-End related tasks, just import <Moment> component and add unix prop:
import Moment from 'react-moment'
// get date variable
const {date} = this.props
<Moment unix>{date}</Moment>
I would like to add that Using the library momentjs in javascript you can have the whole data information in an object with:
const today = moment(1557697070824.94).toObject();
You should obtain an object with this properties:
today: {
date: 15,
hours: 2,
milliseconds: 207,
minutes: 31,
months: 4
seconds: 22,
years: 2019
}
It is very useful when you have to calculate dates.
for people as dumb as myself, my date was in linux epoch
but it was a string instead of an integer, and that's why i was getting
RangeError: Date value out of bounds
so if you are getting the epoch from an api, parseInt it first
var dateTime = new Date(parseInt(1370001284000));
dateTime.toISOString();

Parsing a date in JavaScript?

Is there a way I could get the year, month (0 based) and day from '03/05/2013'
If so, how?
Thanks
Is there a safe way to do it that can check if it is in the correct format?
You have the Date.parse method which parses a Date string and returns its timestamp, so you can call new Date().
Something like this:
new Date(Date.parse('03/06/2013'))
Most easy is using the split() function, i think:
var date = "03/05/2013";
var dateParts = date.split("/");
var day = dateParts[0];
var month = dateParts[1];
var year = dateParts[2];
http://jsfiddle.net/s7ma2/1/

how can change the text string to date object?

i am getting string from server and i need to covert that fetching string in to new date object.. for doing this, i tried this function, but no use, any one can help me to convert strings to date object?
my code is :
var nationZone = {
getNewYorkLocalTime : 'getTime.php?lat=40.71417&lan=74.00639',
getLondonLocalTime : 'getTime.php?lat=51.5&lan=0.1166667',
getChennaiLocalTime : 'getTime.php?lat=13.0833333&lan=80.2833333',
getBangaloreLocalTime:'getTime.php?lat=12.9833333&lan=77.5833333'
}
$.each(nationZone , function(key, value){
$.get(value, function(response){
var newdate = $(response).find('localtime').text();
if(key == "getNewYorkLocalTime"){
var newyourktime = new Date(newdate);
newyourktime.getTime()
}
});
});
but, the newyourktime is showing local time only.. any help please? as well i am getting the response from server is : 17 Nov 2011 18:09:47 - like this.
Use http://www.datejs.com/
As an example:
var newyourktime = Date.parse('2011-11-11, 11:11 AM');
alert(newyourktime.toString('dd/mm/yyyy HH:mm:ss EST'));
Check out the Datejs library documentation to meet your requirements, after your date string is parsed, you can do a lot with it.
This will try to parse the date using the client machine own local settings, which is not good.
Instead of passing it as string, pass it as the total seconds that passed since 1/1/1970 at midnight and use this number when constructing the new Date object of JavaScript.
For example pass this number: 1321614000000 and you will get November 18th 2011, 1 PM
You could use substr
day = newdate.substr(0,2);
month = newdate.substr(3,3);
year = newdate.substr(7,4);
var newyorktime = new Date(year, month, day);
Substr

Categories