Changing date format javascript - javascript

I'm pulling some data from two different APIs and I want to the objects later on.
However, I'm getting two different date formats: this format "1427457730" and this format "2015-04-10T09:12:22Z". How can I change the format of one of these so I have the same format to work with?
$.each(object, function(index) {
date = object[index].updated_at;
}

Here's one option:
var timestamp = 1427457730;
var date = new Date(timestamp * 1000); // wants milliseconds, not seconds
var dateString = date.toISOString().replace(/\.\d+Z/, 'Z'); // remove the ms
dateString will now be 2015-03-27T12:02:10Z.

Try moment.js
var timestamp = 1427457730;
var date = '2015-04-10T09:12:22Z';
var m1 = moment(timestamp);
var m2 = moment(date);
console.log(m1);
console.log(m2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
You can use .format() method in moment to parse the date to whatever format you want, just like:
m2.format('YYYY MMM DD ddd HH:mm:ss') // 2015 Apr 10 Fri 17:12:22
Check out the docs for more format tokens.

What you probably want in javascript, are date objects.
The first string is seconds since epoch, javascript needs milliseconds, so multiply it by 1000;
The second string is a valid ISO date, so if the string contains a hyphen just pass it into new Date.
var date = returned_date.indexOf('-') !== -1 ? returned_date : returned_date * 1000;
var date_object = new Date(date);
Making both types into date objects, you could even turn that into a handy function
function format_date(date) {
return new Date(date.indexOf('-') !== -1 ? date : date * 1000);
}
FIDDLE

Take a look at http://momentjs.com/. It is THE date/time formatting library for JavaScript - very simple to use, extremely flexible.

Related

Material2 Datepicker - Convert date to timestamp without time [duplicate]

Can I convert iso date to milliseconds?
for example I want to convert this iso
2012-02-10T13:19:11+0000
to milliseconds.
Because I want to compare current date from the created date. And created date is an iso date.
Try this
var date = new Date("11/21/1987 16:00:00"); // some mock date
var milliseconds = date.getTime();
// This will return you the number of milliseconds
// elapsed from January 1, 1970
// if your date is less than that date, the value will be negative
console.log(milliseconds);
EDIT
You've provided an ISO date. It is also accepted by the constructor of the Date object
var myDate = new Date("2012-02-10T13:19:11+0000");
var result = myDate.getTime();
console.log(result);
Edit
The best I've found is to get rid of the offset manually.
var myDate = new Date("2012-02-10T13:19:11+0000");
var offset = myDate.getTimezoneOffset() * 60 * 1000;
var withOffset = myDate.getTime();
var withoutOffset = withOffset - offset;
console.log(withOffset);
console.log(withoutOffset);
Seems working. As far as problems with converting ISO string into the Date object you may refer to the links provided.
EDIT
Fixed the bug with incorrect conversion to milliseconds according to Prasad19sara's comment.
A shorthand of the previous solutions is
var myDate = +new Date("2012-02-10T13:19:11+0000");
It does an on the fly type conversion and directly outputs date in millisecond format.
Another way is also using parse method of Date util which only outputs EPOCH time in milliseconds.
var myDate = Date.parse("2012-02-10T13:19:11+0000");
Another option as of 2017 is to use Date.parse(). MDN's documentation points out, however, that it is unreliable prior to ES5.
var date = new Date(); // today's date and time in ISO format
var myDate = Date.parse(date);
See the fiddle for more details.
Yes, you can do this in a single line
let ms = Date.parse('2019-05-15 07:11:10.673Z');
console.log(ms);//1557904270673
Another possible solution is to compare current date with January 1, 1970, you can get January 1, 1970 by new Date(0);
var date = new Date();
var myDate= date - new Date(0);
Another solution could be to use Number object parser like this:
let result = Number(new Date("2012-02-10T13:19:11+0000"));
let resultWithGetTime = (new Date("2012-02-10T13:19:11+0000")).getTime();
console.log(result);
console.log(resultWithGetTime);
This converts to milliseconds just like getTime() on Date object
var date = new Date()
console.log(" Date in MS last three digit = "+ date.getMilliseconds())
console.log(" MS = "+ Date.now())
Using this we can get date in milliseconds
var date = new Date(date_string);
var milliseconds = date.getTime();
This worked for me!
if wants to convert UTC date to milliseconds
syntax : Date.UTC(year, month, ?day, ?hours, ?min, ?sec, ?milisec);
e.g :
date_in_mili = Date.UTC(2020, 07, 03, 03, 40, 40, 40);
console.log('miliseconds', date_in_mili);
In case if anyone wants to grab only the Time from a ISO Date, following will be helpful. I was searching for that and I couldn't find a question for it. So in case some one sees will be helpful.
let isoDate = '2020-09-28T15:27:15+05:30';
let result = isoDate.match(/\d\d:\d\d/);
console.log(result[0]);
The output will be the only the time from isoDate which is,
15:27

How to subtract two different dates from a date/time stamp?

I need to subtract a date like 1/26/2015 from a date-time like 2016-01-27T01:10:57.569000+00:00. From what I've read converting both to distance in milliseconds from Epoch and then subtracting is the easiest way. I've tried using various methods, but all the methods seem to say 2016-01-27T01:10:57.569000+00:00 is invalid data. The method .getTime() works great for the 1/26/2015 format, but it can't read the 2016-01-27T01:10:57.569000+00:00.
How does one go about getting the date/time UTC time into milliseconds?
On a complicated way you can use a regex to extract each part of the date as string and then use them in a new Date with all parameters:
function getTimeDifference(){
var regEx = /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):([\d.]+)/;
var dateString = '2016-01-27T01:10:57.569000+00:00';
var r = regEx.exec( dateString );
var date1 = new Date(r[1], r[2]-1, r[3], r[4], r[5], r[6]); // Notice the -1 in the month
var date2 = new Date('1/26/2015');
var difference = date1 - date2;
Logger.log(difference);
}
I ended up using this. When I call parseDate(), I used getTime() to get the date in milliseconds then subtracted them and converted them to days. For my use case the time didn't have to be down to the second, but if it did, it wouldn't be hard to parse more info from the string. I ran into trouble initially because as a beginner Javascript writer I didn't know why apps script wouldn't accept this format into the date constructor.
function parseDate(str) {
//This should accept 'YYYY-MM-DD' OR '2016-01-27T01:10:57.569000+00:00'
if(str.length == 10){
var mdy = str.split('-');
return new Date(mdy[0], mdy[1]-1, mdy[2]);
}
else
{
var mdy = str.split('-');
var time = mdy[2].split('T');
var hms = time[1].split(':');
return new Date(mdy[0], mdy[1]-1, time[0], hms[0], hms [1]);
}
}
If you are confident that the values in the date strings will always be valid and that the ISO8601 string will always have offset 00:00 (i.e. UTC), then simple parse functions are:
// Parse ISO 8601 format 2016-01-27T01:10:57.569000+00:00
function parseISOUTC(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0],b[1]-1,b[2],b[3],b[4],b[5],b[6]));
}
document.write(parseISOUTC('2016-02-04T00:00:00.000+00:00'));
// Parse US format m/d/y
function parseMDY(s) {
var b = s.split(/\D/);
return new Date(b[2],b[0]-1,b[1]);
}
document.write('<br>'+ parseMDY('2/4/2016'))
document.write('<br>'+ (parseISOUTC('2016-02-04T00:00:00.000+00:00') - parseMDY('2/4/2016')))
Note that the first string is UTC and the second will be treated as local (per ECMAScript 2015), so the difference between 2016-02-04T00:00:00.000+00:00 and 2/4/2016 will be the time zone offset of the host system.

Parsing Date with javascript in FireFox

I have strange date format like this dMMMyyyy (for example 2Dec2013).
I'm trying to create Date object in my javascript code:
var value = "2Apr2014";
var date = new Date(value);
alert(date.getTime());
example
in Google Chrome this code works fine but in FireFox it returns Null
Can anyone suggest something to solve this problem
Thanks.
How about just parsing it into the values new Date accepts, that way it works everywhere
var value = "02Apr2014";
var m = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var month = value.replace(/\d/g,''),
parts = value.split(month),
day = parseInt(parts.shift(), 10),
year = parseInt(parts.pop(), 10);
var date = new Date(year, m.indexOf(month), day);
FIDDLE
This fiddle works in both firefox and chrome
var value = "02 Apr 2014";
var date = new Date(value);
alert(date.getTime())
Check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
I would suggest using something like jQuery datepicker to parse your dates.
I haven't tested it but it seems you'd need something like:
var currentDate = $.datepicker.parseDate( "dMyy", "2Apr2014" );
jsFiddle
Just be aware of:
d - day of month (no leading zero)
dd - day of month (two digit)
M - month name short
y - year (two digit)
yy - year (four digit)
However if for some reason you really wanted to do it yourself, then you could check out this link: http://jibbering.com/faq/#parseDate
It has some interesting examples on parsing dates.
Whilst not exactly what you want, the Extended ISO 8601 local Date format YYYY-MM-DD example could be a good indication of where to start:
/**Parses string formatted as YYYY-MM-DD to a Date object.
* If the supplied string does not match the format, an
* invalid Date (value NaN) is returned.
* #param {string} dateStringInRange format YYYY-MM-DD, with year in
* range of 0000-9999, inclusive.
* #return {Date} Date object representing the string.
*/
function parseISO8601(dateStringInRange) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
date = new Date(NaN), month,
parts = isoExp.exec(dateStringInRange);
if(parts) {
month = +parts[2];
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
}
}
return date;
}
You can use following JavaScript Library for uniform date parser across browser.
It has documentation
JSFIDDLE
code:
var value = "2Apr2014";
var date =new Date(dateFormat(value));
alert(date.getTime());

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();

Convert date from string in javascript

i need to convert from a date in string format like this "2011-05-12 16:50:44.055" to the number of milliseconds since midnight 1 January 1970 date format in Javascript
To ensure correct cross-browser behaviour, I think you should parse the string yourself. I moulded this answer into:
function msFromString(dateAsString)
{
var parts = dateAsString.match(/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}).(\d{3})/);
return new Date(parts[1],
parts[2] - 1,
parts[3],
parts[4],
parts[5],
parts[6],
parts[7]).getTime();
}
console.log(msFromString("2011-05-12 16:50:44.055"));
This outputs 1305211844055.
This works everywhere including Safari5 and Fx5 on OSX
DEMO HERE
Without milliseconds:
var date_test = new Date("2011-07-14 11:23:00".replace(/-/g,"/"));
WITH milliseconds in the timestamp
var timestamp = "2011-05-12 16:50:44.055";
var dateParts = timestamp.split(".");
var date_test = new Date(dateParts[0].replace(/-/g,"/"));
var millisecs = date_test.getTime()+parseInt("1"+dateParts[1]);
alert(millisecs+"\n"+new Date(2011,4,12,16,50,44,55).getTime());
Have you tried the Date.parse() method? It should recognise this format (though I haven't tested that). The return value should be the number of milliseconds since 01/01/1970.
Make a Date object from the date string and use the getTime() method to get the milliseconds since 1 January 1970. http://www.w3schools.com/jsref/jsref_obj_date.asp
var date = new Date("2011-05-12 16:50:44.055");
document.write(date.getTime());

Categories