Javascript date format using string month - javascript

All the other topics on date format assume that dates are entered as integers.
I'm writing a script (Linux) that requires the month to be a string (Jan, Feb, Mar etc) and need to validate the dates.
I've written a clunky routine that extracts the month, determines the month number and then does the comparison but I was hoping there might be something neater out there to do this? I thought I had seen something about using a 'format' method but I can't find it now...
I've tried this but it fails miserably:
var checkDate1 = document.getElementById('fromDate').value;
var checkDate2 = document.getElementById('toDate').value;
tmpDate1 = new Date(checkDate1);
tmpDate2 = new Date(checkDate2);
if (tmpDate1 < tmpDate2) {
where a typical field entry will be '12-may-2012', for example.
NOTE: I don't have access to add any fancy, whizzy libraries to the system so have to make do with the vanilla stuff.

In JavaScript, to be parsed in the constructor, string Date must have the format : D, d M Y H:i:s
Now it'll be : Tue, 29 May 2012 15:22:59
If you want to stay with string, you'll have to make a fancy function that parse your value, and find what day will be the 29 May of 2012.
Another method ( and easier ) is to create a new Date, parse you value and use the on of the other constructors
var today = '05-29-2012',
aToday = today.split('-'),
dToday = new Date(aToday[2], aToday[0], aToday[1], 0, 0, 0, 0),
tomorrow = '05-30-2012',
aTomorrow = tomorrow.split('-'),
dTomorrow = new Date(aTomorrow[2], aTomorrow[0], aTomorrow[1], 0, 0, 0, 0);
if (dTomorrow.getTime() > dToday.getTime() ) {
console.log('Tomorrow is tomorrow');
} else {
console.log('Tomorrow is not tomorrow');
}

Related

javascript - compare dates in different formats

I have 2 dates which I need to compare to see if one is greater than the other but they are in different formats and I'm not sure of the best way to compare the 2.
The formats are:
1381308375118 (this is var futureDate)
which is created by
var today = new Date(); today.setHours(0, 0, 0, 0); var futureDate = new Date().setDate(today.getDate() + 56); //56 days in the future...
And the other format is
2013/08/26
Any ideas how I can compare the 2?
Without using a 3rd party library, you can create new Date objects using both those formats, retrieve the number of milliseconds (since midnight Jan 1, 1970) using getTime() and then simply use >:
new Date("2013/08/26").getTime() > new Date(1381308375118).getTime()
I strongly recommend using datejs library.
Thus this can be written in one single line:
Date.today().isAfter(Date.parse('2013/08/26'))
I would make sure that I am comparing the "date" element of each format and exclude any "time" element. Then with both dates converted to milliseconds, simply compare the values. You could do something like this. If dates are equal it returns 0, if the first date is less that the second then return -1, otherwise return 1.
Javascript
function compareDates(milliSeconds, dateString) {
var year,
month,
day,
tempDate1,
tempDate2,
parts;
tempDate1 = new Date(milliSeconds);
year = tempDate1.getFullYear();
month = tempDate1.getDate();
day = tempDate1.getDay();
tempDate1 = new Date(year, month, day).getTime();
parts = dateString.split("/");
tempDate2 = new Date(parts[0], parts[1] - 1, parts[2]).getTime();
if (tempDate1 === tempDate2) {
return 0;
}
if (tempDate1 < tempDate2) {
return -1;
}
return 1;
}
var format1 = 1381308375118,
format2 = "2013/08/26";
console.log(compareDates(format1, format2));
On jsfiddle
Maybe you can use Date.parse("2013/08/26") and compare with former one
Follow these steps to compare dates
Each of your date must to passed through Date object i.e. new Date(yourDate).
Now dates will have same format and these will be comparable
let date1 = new Date()
let date2 = "Jan 1, 2019"
console.log(`Date 1: ${date1}`)
console.log(`Date 2: ${date2}`)
let first_date = new Date(date1)
let second_date = new Date(date2)
// pass each of the date to 'new Date(yourDate)'
// and get the similar format dates
console.log(`first Date: ${first_date}`)
console.log(`second Date: ${second_date}`)
// now these dates are comparable
if(first_date > second_date) {
console.log(`${date2} has been passed`)
}

Epoch time .NET to JavaScript (hour off?)

Using the following code in .NET
Input: "2011-09-14 00:00:00.0000000" (From an SQL datebase loaded into a Date datetype becoming #9/14/2011#)
<Extension()>
Public Function ToEpoch(value As Date) As Double
Dim span As TimeSpan = (value - New Date(1970, 1, 1, 0, 0, 0, 0).ToLocalTime)
Return span.TotalMilliseconds
End Function
And this in JavaScript
var StartDate = new Date(<%= StartDate() %>);
Resulting in this output
var StartDate = new Date(1315922400000);
It appears that only for this specific input the StartDate (on the javascript side) is exactly one hour off.
Resulting in the JavaScript datetime of: Tue Sep 13 23:00:00 UTC+1000 2011
If I input a value like Date.Now it appears to function correctly.
I assume I'm missing something fundamental?
Seems to me that unix epoch is Jan 1, 1970, UTC.
In light of that, your creation of the Date and then conversion to local time is somewhat backwards. What you need to do is convert the variable time value to UTC.
<Extension()>
Public Function ToEpoch(value As Date) As Double
Dim span As TimeSpan = (value.ToUniversalTime -
New System.DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
Return span.TotalMilliseconds
End Function
You may think the two conversions are equivalent, but they may not be, as explained in
http://blogs.msdn.com/b/oldnewthing/archive/2003/10/24/55413.aspx .
I suspect the two dates have different daylight savings values. See if the following calls to IsDaylightSavingTime() return the same values:
Dim dt As Date = new Date(2011, 9, 14)
Dim epoch As Date = new Date(1970, 1, 1)
dt.IsDaylightSavingTime()
epoch.IsDaylightSavingTime()

the closest Sunday before given date with JavaScript

I need to know the date for last Sunday for given date in php & javascript
Let's have a function give_me_last_Sunday
give_me_last_Sunday('20110517') is 20110515
give_me_last_Sunday('20110604') is 20110529
The full backup is done on Sundays = weekly. If I want to restore daily backup I need full (weekly) and daily backup. I need to copy backup files before restoring to temp directory so I restoring daily backup I need to know what weekly backup file I need to copy along the daily file.
My thought was to get Julian representation (or something similar) for the given date and then subtract 1 and check if it is Sunday ... Not sure if this is the best idea and how to convert given date into something I can subtract.
Based on Thomas' effort, and provided the input string is exactly the format you specified, then:
function lastSunday(d) {
var d = d.replace(/(^\d{4})(\d{2})(\d{2}$)/,'$1/$2/$3');
d = new Date(d);
d.setDate(d.getDate() - d.getDay());
return d;
}
Edit
If I were to write that now, I'd not depend on the Date object parsing the string but do it myself:
function lastSunday(s) {
var d = new Date(s.substring(0,4), s.substring(4,6) - 1, s.substring(6));
d.setDate(d.getDate() - d.getDay());
return d;
}
While the format yyyy/mm/dd is parsed correctly by all browsers I've tested, I think it's more robust to stick to basic methods. Particularly when they are likely more efficient.
Ok so this is for JavaScript only. You have an input that you need to extract the month, date, and year from. The following is just partly an answer then on how to get the date:
<script type="text/javascript">
var myDate=new Date();
myDate.setFullYear(2011,4,16)
var a = myDate.getDate();
var t = myDate.getDay();
var r = a - t;
document.write("The date last Sunday was " + r);
</script>
So the setFullYear function sets the myDate to the date specified where the first four digits is the year, the next are is the month (0= Jan, 1= Feb.,...). The last one is the actually date. Then the above code gives you the date of the Sunday before that. I am guessing that you can add more code to get the month (use getMonth() method). Here are a few links that might be helpful
http://www.w3schools.com/js/js_obj_date.asp
http://www.w3schools.com/jsref/jsref_setFullYear.asp
http://www.w3schools.com/jsref/jsref_getMonth.asp
(You can probably find the other functions that you need)
I hope this helps a bit even though it is not a complete answer.
Yup and strtotime has been ported to JS for eg http://phpjs.org/functions/strtotime:554 here.
final code (big thanks to #Thomas & #Rob)
function lastSunday(d) {
var d = d.replace(/(^\d{4})(\d{2})(\d{2}$)/,'$1/$2/$3');
d = new Date(d);
d.setDate(d.getDate() - d.getDay());
year = d.getFullYear()+'';
month = d.getMonth()+1+'';
day = d.getDate()+'';
if ( month.length == 1 ) month = "0" + month; // Add leading zeros to month and date if required
if ( day.length == 1 ) day = "0" + day;
return year+month+day;
}

Validate two dates of this "dd-MMM-yyyy" format in javascript

I have two dates 18-Aug-2010 and 19-Aug-2010 of this format. How to find whether which date is greater?
You will need to create a custom parsing function to handle the format you want, and get date objects to compare, for example:
function customParse(str) {
var months = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'],
n = months.length, re = /(\d{2})-([a-z]{3})-(\d{4})/i, matches;
while(n--) { months[months[n]]=n; } // map month names to their index :)
matches = str.match(re); // extract date parts from string
return new Date(matches[3], months[matches[2]], matches[1]);
}
customParse("18-Aug-2010");
// "Wed Aug 18 2010 00:00:00"
customParse("19-Aug-2010") > customParse("18-Aug-2010");
// true
You can do the parsing manually, for your given format, but I'd suggest you use the date.js library to parse the dates to Date objects and then compare.
Check it out, its awesome!
And moreover, its a great addition to your js utility toolbox.
The native Date can parse "MMM+ dd yyyy", which gives:
function parseDMY(s){
return new Date(s.replace(/^(\d+)\W+(\w+)\W+/, '$2 $1 '));
}
+parseDMY('19-August-2010') == +new Date(2010, 7, 19) // true
parseDMY('18-Aug-2010') < parseDMY('19-Aug-2010') // true
Firstly, the 'dd-MMM-yyyy' format isn't an accepted input format of the Date constructor (it returns an "invalid date" object) so we need to parse this ourselves. Let's write a function to return a Date object from a string in this format.
function parseMyDate(s) {
var m = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'];
var match = s.match(/(\d+)-([^.]+)-(\d+)/);
var date = match[1];
var monthText = match[2];
var year = match[3];
var month = m.indexOf(monthText.toLowerCase());
return new Date(year, month, date);
}
Date objects implicitly typecast to a number (milliseconds since 1970; epoch time) so you can compare using normal comparison operators:
if (parseMyDate(date1) > parseMyDate(date2)) ...
Update: IE10, FX30 (and likely more) will understand "18 Aug 2010" without the dashes - Chrome handles either
so Date.parse("18-Aug-2010".replace("/-/g," ")) works in these browsers (and more)
Live Demo
Hence
function compareDates(str1,str2) {
var d1 = Date.parse(str1.replace("/-/g," ")),
d2 = Date.parse(str2.replace("/-/g," "));
return d1<d2;
}

creating date from a timestring in javascript

I am new to javascript and am trying to compare two date values ,I am getting two time value strings in the format
06:30:47 AM
01:10:47 PM
I need to compare these to find out if the first one is less than the other.I couldn't figure out how to do this in javascript.Can someone help?
o.h
I do not think that the standard implementation can parse this. I would do something like this:
function toDate(dateString) {
var timeComponents = dateString.replace(/\s.*$/, '').split(':');
if (dateString.indexOf("PM") > -1) {
timeComponents[0] += 12;
}
var date = new Date();
date.setHours(timeComponents[0]);
date.setMinutes(timeComponents[1]);
date.setSeconds(timeComponents[2]);
return date;
}
if (toDate('06:30:47 AM') > toDate('01:10:47 PM')) {
// ...
}
JavaScript's specified date/time parsing, what you can rely upon cross-browser, is surprisingly limited. For a long time, there was no single string date format that was mandated in the spec, and as of the recent 5th edition spec, the only mandated format is ISO-8601 (and some subsets). You can't yet rely on browsers having implemented that part of the 5th edition spec.
So you have a couple of choices:
Parse the string yourself and use the Date constructor that takes the individual parts of the date as numbers, e.g. new Date(year, month, day, hour, minute, second, ...). (You need only specify as many of those as you want, so for instance new Date(2010, 9, 14) is September 14th, 2010.)
Use a library like Moment that's already done the work for you. Moment lets you specify the format to parse.
Use the Date object. Check this: http://www.w3schools.com/jsref/jsref_obj_date.asp
Try putting the two values in Date variables and do this:
if(var1.valueOf() > var2.valueOf())
{
//Do Something
}
If your times are always in the format 00:00:00 AM then
var a="06:30:47 AM";
var b="01:10:47 PM";
var at=parseInt(a.substring(0,8).replace(/(^0+|:)/g,""));
var bt=parseInt(b.substring(0,8).replace(/(^0+|:)/g,""));
if (a.charAt(9)=="P") {at=at+120000};
if (b.charAt(9)=="P") {bt=bt+120000};
if (at<bt) {
// a is smaller
}
else
{
// a is not smaller
};
..should be cross-browser and time/format safe.
I tried something like this
var ts1="06:30:47 AM";
var ts2="01:10:47 PM";
var ds=new Date().toDateString();
var d1=new Date(ds+" "+ts1);
var d2=new Date(ds+" "+ts2);
if (!(d2>d1)){
alert("d1 should be less than d2");
}
Is there something wrong with this?
// specific formatter for the time format ##:##:## #M
var formatToMiliseconds = function(t){
t = t.split(/[:\s]/);
t = ((t[0] * 3600000) + (t[1] * 60000) * (t[2] * 1000)); // To ms
t = t + (/PM/i.test(t[3]) ? 43200000 : 0); // adjust for AM/PM
return t;
}
var time01 = formatToMiliseconds('06:30:47 AM');
var time02 = formatToMiliseconds('01:10:47 PM');
alert(time01 > time02); // false
allert(time01 < time02); // true
As a bonus, your time is now more compatible with the Date object and other time calculations.

Categories

Resources