I have a 2 different date formats. 1) dd/mm/yyyy 2) dd-mm-yyyy
I want to compare these 2 date formats in Javascript or Actionscript.
Is it possible?
In Javascript:
x = new Date("12/12/1999")
Sun Dec 12 1999 00:00:00 GMT-0500 (Eastern Standard Time)
y = new Date("12-13-1999")
Mon Dec 13 1999 00:00:00 GMT-0500 (Eastern Standard Time)
x == y
false
x < y
true
Hope this helps!
The easy way in AS3 with your date in String format and if you are not interesting in the Date object itself :
var date1Str:String="10/01/2010";
var date2Str:String="10-01-2010";
var equal:Boolean=date2Str.split("-").join("/")==date1Str;
trace(equal);
If you are interesting into the date object so in AS3:
var date1Str:String = "10/01/2010";
var date2Str:String = "10-01-2010";
var date1Arr:Array = date1Str.split("/");
var date2Arr:Array = date2Str.split("-");
var date1:Date = new Date(date1Arr[2], date1Arr[1] - 1, date1Arr[0]);
var date2:Date = new Date(date2Arr[2], date2Arr[1] - 1, date2Arr[0]);
var equal:Boolean = date1.getTime() == date2.getTime();
trace(equal);
You could convert the date strings to Date instances and compare them, I guess.
function parseDate(ds) {
var rv = null;
ds.replace(/(\d\d?)[-/](\d\d?)[-/](\d\d\d\d)/, function(_, dd, mm, yyyy) {
rv = new Date(parseInt(yyyy, 10), parseInt(mm, 10) - 1, parseInt(dd, 10));
});
return rv;
}
// ...
if (parseDate(d1).getTime() === parseDate(d2).getTime()) {
// ...
}
If you wanted to get fancy you could add code to cope with 2-digit years.
[edit] wow #Pete here I am a grown man and somehow I managed to avoidletting the native Date object parse date strings for me all this time :-)
Related
I need to find out if two dates the user selects are the same in Javascript. The dates are passed to this function in a String ("xx/xx/xxxx").That is all the granularity I need.
Here is my code:
var valid = true;
var d1 = new Date($('#datein').val());
var d2 = new Date($('#dateout').val());
alert(d1+"\n"+d2);
if(d1 > d2) {
alert("Your check out date must be after your check in date.");
valid = false;
} else if(d1 == d2) {
alert("You cannot check out on the same day you check in.");
valid = false;
}
The javascript alert after converting the dates to objects looks like this:
Tue Jan 25 2011 00:00:00 GMT-0800 (Pacific Standard Time)
Tue Jan 25 2011 00:00:00 GMT-0800 (Pacific Standard Time)
The test to determine if date 1 is greater than date 2 works. But using the == or === operators do not change valid to false.
Use the getTime() method. It will check the numeric value of the date and it will work for both the greater than/less than checks as well as the equals checks.
EDIT:
if (d1.getTime() === d2.getTime())
If you don't want to call getTime() just try this:
(a >= b && a <= b)
var d1 = new Date($('#datein').val());
var d2 = new Date($('#dateout').val());
use two simple ways to check equality
if( d1.toString() === d2.toString())
if( +d1 === +d2)
var date = Wed Oct 07 2015 19:48:08 GMT+0200 (Central European Daylight Time);
var dateOne = new Date(date);
var dateTwo = new Date();
var isEqual = dateOne.getDate() === dateTwo.getDate()
this will give you the dates equality
I tried many times to convert utc datetime to local datetime,and I have failed. My utc datetime format is
Fri Mar 8 23:12:27 UTC+0200 2013
Also my JavaScript code is
var time = Date(param_time);//param_time is /Date(1362866006646)/
And then time is being Sun Mar 10 00:21:54 UTC+0200 2013 I need to datetime as 2008-01-28T20:24:17Z because I will convert local datetime to pretty datetime.
http://ejohn.org/files/pretty.js
How can I do this ? I looked at many questions on stackoverflow but no one does it work. Thank you.
In order to format your Date correctly use toISOString():
var time = param_time.toISOString();
Note that param_time needs to be a valid Date object.
References
MDN: Date (sections: Syntax, Example: ISO 8601 formatted dates)
I rarely use javascript and all this date time conversion are mystery to me as well, javascript is a client side technology and all this "UTC" phrases means nothing (at least to me), as all the kind of getUTC...()/setUTC...() functions works in local time, the same is goes for all Date.to...String() functions, even the new Date() (that due to the docs) s'd be initialized in UTC, also give a local time.
However, if you have a (correct) date in UTC and wish to convert it to current (client side) local time, then you need getTimezoneOffset(), or shortly:
function UTCToLocalTime(d) {
var timeOffset = -((new Date()).getTimezoneOffset()/60);
d.setHours(d.getHours() + timeOffset);
return d;
}
var time = new Date(Date.parse('Fri Mar 8 23:12:27 UTC+0200 2013'));
alert(UTCToLocalTime(time)); // Sat Mar 9 01:12:27 UTC+0200 2013
//p.s. or...
function UTCToLocalTime2(d)
{
return new Date(d.toString().replace(/UTC.*/g,"") + d.getYear());
}
var timezone = "UTC+01:30";
var start = new Date();
if(timezone != "UTC"){
timezone = timezone.replace(/UTC/g,"");
znak = timezone.charAt(0);
timezone = timezone.replace(/[+|-]/g,"");
timezone = timezone.split(":");
//var start = new Date(start.toString() + " " + timezone);e.
//alert(start.toString());
if(znak == "+") start = new Date(start.getTime() + (timezone[0]*60*60000 + timezone[1] * 60000) );
if(znak == "-") start = new Date(start.getTime() - (timezone[0]*60*60000 + timezone[1] * 60000) );
}
var hours = start.getUTCHours();
var minutes = start.getUTCMinutes();
var seconds = start.getUTCSeconds();
var day = 10;
var month = 04;
var year = 2015;
var dateUtc = Date.UTC(year, month - 1, day + 1, 0, 0, 0);
> 1428710400000
var toDate = new Date(dateUtc);
> Fri Apr 10 2015 21:00:00 GMT-0300 (Hora oficial do Brasil)
I'm have a startDate and a endDate stored in a SQLite database and need to calculate the difference in minutes and seconds between the 2 datetimes using javascript.
For example:
startDate = 2012-10-07 11:01:13
endDate = 2012-10-07 12:42:13
I've had a good read though loads of similar questions on SO but could only find things relating to calculating this as part of a select.
Convert the strings to a JS Date Object, subtract the dates, and use some aritmethic to calculate hours/seconds from the result. Something like:
function convertMS(ms) {
var d, h, m, s, ts, tm, th;
s = ts = Math.floor(ms / 1000);
m = tm = Math.floor(s / 60);
s = s % 60;
h = th = Math.floor(m / 60);
m = m % 60;
d = Math.floor(h / 24);
h = h % 24;
return { d: d, h: h, m: m, s: s, tm: tm, th: th, ts: ts};
};
var start = new Date('2012-10-07 11:01:13'.split('-').join('/'))
,end = new Date('2012-10-07 12:42:13'.split('-').join('/'))
,dif = convertMS(end - start);
console.log(dif.h+':'+dif.m); //=> 1:41
console.log('total minutes dif: '+dif.tm); //=> total minutes dif: 101
console.log('total seconds dif: '+dif.ts); //=> total seconds dif: 6060
[edit based on comment]
'Manual' parsing of a date string in the provided format:
Date.tryParse = function(ds){
var arr = ds.match(/\d+/g)
,err = 'Expected at least yyyy'
,dat = arr.length && String(arr[0]).length === 4
? doParse.apply(null,arr) : err;
return dat;
function doParse(y,m,d,h,mi,s,ms){
var dat = new Date(+y,(+m-1)||0,+d||1,+h||0,+mi||0,+s||0,+ms||0);
return isNaN(dat) ? new Date : dat;
}
}
var start = Date.tryParse('2012-10-07 11:01:13'); //=> Sun Oct 07 2012 11:01:13
var test = Date.tryParse('2009'); //=> Sun Jan 01 2009 00:00:00
All the answers are generally correct with respect to converting the dates to milliseconds in epoch time, subtracting those, and converting the result back from milliseconds into your required units (although the specific implementations offered elsewhere do not currently give you exactly what you asked for -- i.e., just the number of minutes and seconds between your two datetimes).
However, please also note...
new Date('2012-10-07 12:42:13')
... that this is not a reliable way to construct the Date from your SQLite date strings.
When you feed a string into the constructor of a Date object, you are effectively calling Date.parse(). That behaves differently on different browsers.
Check this out:
> new Date('1-1-2012');
Sun Jan 01 2012 00:00:00 GMT-0800 (PST)
> new Date('01-01-2012');
Sun Jan 01 2012 00:00:00 GMT-0800 (PST)
> new Date('2012-1-1');
Sun Jan 01 2012 00:00:00 GMT-0800 (PST)
Looks pretty good, right? But that's on Chrome.
Now check out what happens in an up-to-date version of Firefox, with the exact same calls:
> new Date('1-1-2012');
Date {Invalid Date}
> new Date('01-01-2012');
Date {Invalid Date}
> new Date('2012-1-1');
Date {Invalid Date}
> new Date('2012-01-01');
Date {Sat Dec 31 2011 16:00:00 GMT-0800 (PST)}
Furthermore, look at this behavior, in both browsers:
> new Date('2012-01-01');
Sat Dec 31 2011 16:00:00 GMT-0800 (PST)
Simply prepending zeroes to the month and date digits causes a time warp! You have to set the time and a timezone (for me, PST) to make that go away:
> new Date('2012-01-01T00:00:00-08:00')
Sun Jan 01 2012 00:00:00 GMT-0800 (PST)
Basically, dealing with date string parsing is a headache. You don't want to have to digest and account for specs like this, this, and this.
So, here's a better alternative -- pass the parts of your datetime as separate args to the constructor of the Date object. That will reliably create the date for you, so your subsequent comparisons are valid.
new Date(year, month, day [, hour, minute, second, millisecond])
Here's what that initialization could look like for your case:
// Extract month, day, year from SQLite format, 'trimming' whitespace.
var sqlLiteSampleStr = "2012-10-07 11:01:13";
var re = /^\s*(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\s*$/;
var match = re.exec(sqlLiteSampleStr);
if (match) {
var year = parseInt(match[1]);
var month = parseInt(match[2]) - 1; // Zero-indexed months.
var date = parseInt(match[3]);
var hour = parseInt(match[4]);
var minute = parseInt(match[5]);
var second = parseInt(match[6]);
var date = new Date(year, month, date, hour, minute, second);
}
Note: be careful of timezone considerations. You don't seem to have any timezone data in that SQLite format snippet.
Update
#james-j clarified that he's looking for minutes and seconds specifically.
Here's a snippet to extract just minutes and seconds:
var msPerMin = 1000 * 60;
var min = Math.floor(timeInMs / msPerMin);
var timeInMs = timeInMs - (min * msPerMin);
var sec = Math.floor(timeInMs / 1000 );
Other answers are correct, however browsers do not consistently parse date strings (see below) so you should manually parse the strings. The format in the OP is not consistent with the format in ES5 either, and will not be correctly parsed by some browsers. A simple function to convert the OP format to a date that will work in all browsers is:
function stringToDate(s) {
s = s.split(/[-\/\. :]/);
return new Date(s[0], --s[1], s[2], s[3], s[4], s[5], 0)
}
There are some formats that are parsed by all browsers, however they are not standards compliant and if used, are dependent on all implementations continuing to support unspecified formats.
Edit
To tolerate malformed input (extra whitespace, different seperators, extra characters), match can be used instead of split:
function stringToDate(s) {
s = s.match(/\d+/g);
return new Date(s[0], --s[1], s[2], s[3], s[4], s[5], 0)
}
However, since the values are coming from a database and a format has been specified, the date strings should fit the format. Erroneous data should not be stored in the first place.
For completeness, here's a function to do what you want:
/* Return difference between two dates as minutes and seconds mm:ss.
* Input format is yyyy-mm-dd hh:mm:ss
* If strings don't converted to dates (incorrect format or invalid values),
* return undefined.
*/
function diffInMins(s0, s1) {
var diff;
// Convert strings to date ojbects
var d0 = stringToDate(s0);
var d1 = stringToDate(s1);
// Helper function to padd with leading zero
function z(n) {
return (n<10? '0' : '') + n;
}
// Check conversions
if (d0 && d1 && typeof d0 == 'object' && typeof d1 == 'object') {
// Return difference formatted as mm:ss
if (d0 && d1) {
diff = d1 - d0;
return z(diff/60000 | 0) + ':' + z(Math.round(diff%60000/1000));
}
}
}
JavaScript actually makes subtracting dates quite simple. Here's how it works:
// Create Date objects from the strings
startDate = new Date('2012-10-07 11:01:13');
endDate = new Date('2012-10-07 12:42:13');
// Subtract Date objects to return milliseconds between them
millisecondsBetween = (endDate - startDate);
// Convert to whatever you like
alert(millisecondsBetween/1000/60 + ' minutes');
I'm a bit of a rambler, but I'll try to keep this clear -
I'm bored, so I'm working on a "shoutbox", and I'm a little confused over one thing. I want to get the time that a message is entered, and I want to make sure I'm getting the server time, or at least make sure I'm not getting the local time of the user. I know it doesn't matter, since this thing won't be used by anyone besides me, but I want to be thorough. I've looked around and tested a few things, and I think the only way to do this is to get the milliseconds since January 1, 1970 00:00:00 UTC, since that'd be the same for everyone.
I'm doing that like so:
var time = new Date();
var time = time.getTime();
That returns a number like 1294862756114.
Is there a way to convert 1294862756114 to a more readable date, like DD/MM/YYYY HH:MM:SS?
So, basically, I'm looking for JavaScript's equivalent of PHP's date(); function.
var time = new Date().getTime(); // get your number
var date = new Date(time); // create Date object
console.log(date.toString()); // result: Wed Jan 12 2011 12:42:46 GMT-0800 (PST)
If you want custom formatting for your date I offer a simple function for it:
var now = new Date;
console.log( now.customFormat( "#DD#/#MM#/#YYYY# #hh#:#mm#:#ss#" ) );
Here are the tokens supported:
token: description: example:
#YYYY# 4-digit year 1999
#YY# 2-digit year 99
#MMMM# full month name February
#MMM# 3-letter month name Feb
#MM# 2-digit month number 02
#M# month number 2
#DDDD# full weekday name Wednesday
#DDD# 3-letter weekday name Wed
#DD# 2-digit day number 09
#D# day number 9
#th# day ordinal suffix nd
#hhhh# 2-digit 24-based hour 17
#hhh# military/24-based hour 17
#hh# 2-digit hour 05
#h# hour 5
#mm# 2-digit minute 07
#m# minute 7
#ss# 2-digit second 09
#s# second 9
#ampm# "am" or "pm" pm
#AMPM# "AM" or "PM" PM
And here's the code:
//*** This code is copyright 2002-2016 by Gavin Kistner, !#phrogz.net
//*** It is covered under the license viewable at http://phrogz.net/JS/_ReuseLicense.txt
Date.prototype.customFormat = function(formatString){
var YYYY,YY,MMMM,MMM,MM,M,DDDD,DDD,DD,D,hhhh,hhh,hh,h,mm,m,ss,s,ampm,AMPM,dMod,th;
YY = ((YYYY=this.getFullYear())+"").slice(-2);
MM = (M=this.getMonth()+1)<10?('0'+M):M;
MMM = (MMMM=["January","February","March","April","May","June","July","August","September","October","November","December"][M-1]).substring(0,3);
DD = (D=this.getDate())<10?('0'+D):D;
DDD = (DDDD=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][this.getDay()]).substring(0,3);
th=(D>=10&&D<=20)?'th':((dMod=D%10)==1)?'st':(dMod==2)?'nd':(dMod==3)?'rd':'th';
formatString = formatString.replace("#YYYY#",YYYY).replace("#YY#",YY).replace("#MMMM#",MMMM).replace("#MMM#",MMM).replace("#MM#",MM).replace("#M#",M).replace("#DDDD#",DDDD).replace("#DDD#",DDD).replace("#DD#",DD).replace("#D#",D).replace("#th#",th);
h=(hhh=this.getHours());
if (h==0) h=24;
if (h>12) h-=12;
hh = h<10?('0'+h):h;
hhhh = hhh<10?('0'+hhh):hhh;
AMPM=(ampm=hhh<12?'am':'pm').toUpperCase();
mm=(m=this.getMinutes())<10?('0'+m):m;
ss=(s=this.getSeconds())<10?('0'+s):s;
return formatString.replace("#hhhh#",hhhh).replace("#hhh#",hhh).replace("#hh#",hh).replace("#h#",h).replace("#mm#",mm).replace("#m#",m).replace("#ss#",ss).replace("#s#",s).replace("#ampm#",ampm).replace("#AMPM#",AMPM);
};
You can simply us the Datejs library in order to convert the date to your desired format.
I've run couples of test and it works.
Below is a snippet illustrating how you can achieve that:
var d = new Date(1469433907836);
d.toLocaleString(); // expected output: "7/25/2016, 1:35:07 PM"
d.toLocaleDateString(); // expected output: "7/25/2016"
d.toDateString(); // expected output: "Mon Jul 25 2016"
d.toTimeString(); // expected output: "13:35:07 GMT+0530 (India Standard Time)"
d.toLocaleTimeString(); // expected output: "1:35:07 PM"
Below is a snippet to enable you format the date to a desirable output:
var time = new Date();
var time = time.getTime();
var theyear = time.getFullYear();
var themonth = time.getMonth() + 1;
var thetoday = time.getDate();
document.write("The date is: ");
document.write(theyear + "/" + themonth + "/" + thetoday);
Try using this code:
var datetime = 1383066000000; // anything
var date = new Date(datetime);
var options = {
year: 'numeric', month: 'numeric', day: 'numeric',
};
var result = date.toLocaleDateString('en', options); // 10/29/2013
See more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
Try using this code:
var milisegundos = parseInt(data.replace("/Date(", "").replace(")/", ""));
var newDate = new Date(milisegundos).toLocaleDateString("en-UE");
Enjoy it!
so you need to pass that var time after getTime() into another new Date()
here is my example:
var time = new Date()
var time = time.getTime()
var newTime = new Date(time)
console.log(newTime)
//Wed Oct 20 2021 15:21:12 GMT+0530 (India Standard Time)
here output is my datetime standard format for you it will be in country format
if you want it in another format then you can apply another date function on var newTime
like
var newTime = new Date(time).toDateString()
console.log(newTime)
//Wed Oct 20 2021
Try this one :
var time = new Date().toJSON();
One line code.
var date = new Date(new Date().getTime());
or
var date = new Date(1584120305684);
/Date(1383066000000)/
function convertDate(data) {
var getdate = parseInt(data.replace("/Date(", "").replace(")/", ""));
var ConvDate= new Date(getdate);
return ConvDate.getDate() + "/" + ConvDate.getMonth() + "/" + ConvDate.getFullYear();
}
Assume the date as milliseconds date is 1526813885836, so you can access the date as string with this sample code:
console.log(new Date(1526813885836).toString());
For clearness see below code:
const theTime = new Date(1526813885836);
console.log(theTime.toString());
use datejs
new Date().toString('yyyy-MM-d-h-mm-ss');
I need to find out if two dates the user selects are the same in Javascript. The dates are passed to this function in a String ("xx/xx/xxxx").That is all the granularity I need.
Here is my code:
var valid = true;
var d1 = new Date($('#datein').val());
var d2 = new Date($('#dateout').val());
alert(d1+"\n"+d2);
if(d1 > d2) {
alert("Your check out date must be after your check in date.");
valid = false;
} else if(d1 == d2) {
alert("You cannot check out on the same day you check in.");
valid = false;
}
The javascript alert after converting the dates to objects looks like this:
Tue Jan 25 2011 00:00:00 GMT-0800 (Pacific Standard Time)
Tue Jan 25 2011 00:00:00 GMT-0800 (Pacific Standard Time)
The test to determine if date 1 is greater than date 2 works. But using the == or === operators do not change valid to false.
Use the getTime() method. It will check the numeric value of the date and it will work for both the greater than/less than checks as well as the equals checks.
EDIT:
if (d1.getTime() === d2.getTime())
If you don't want to call getTime() just try this:
(a >= b && a <= b)
var d1 = new Date($('#datein').val());
var d2 = new Date($('#dateout').val());
use two simple ways to check equality
if( d1.toString() === d2.toString())
if( +d1 === +d2)
var date = Wed Oct 07 2015 19:48:08 GMT+0200 (Central European Daylight Time);
var dateOne = new Date(date);
var dateTwo = new Date();
var isEqual = dateOne.getDate() === dateTwo.getDate()
this will give you the dates equality