I have some code that looks like this:
<h3>Thursday Sep 10</h3>
<ul>great stuff in here</ul>
<h3>Friday Sep 18</h3>
<ul>other stuff in here</ul>
They have a basic jQuery hidey-showy thing happening: click on the H3, and the UL underneath expands or contracts. By default they are all showing/open.
I'd like to set it up so that any date that has passed (like Sep 10 in this example) is contracted by default.
I don't seem to be able to get my CMS to spit out a nice compare-able date (like epoch time) to use as an ID for the H3. Is there a way I can use js's Date() function to build something like that out of the existing information ("Thursday Sep 10"), or some other way entirely to get this done?
(All of the dates are in 2009 and the site won't exist in 2010, so hardcoding the year into any functions is A-OK if that's what needs to be done.)
Thanks!
The first hurdle is to convert your text dates into valid strings that can initialize JavaScript date objects.
The conversion process (including valid string formats) is covered on http://programming.top54u.com/post/Javascript-Convert-String-to-Date.aspx.
Unfortunately, your text representations are not valid inputs for the JavaScript Date constructor. You will need to write a function to convert your strings into a valid representation before using them in the Date constructor.
Once you have your Date objects initialized, you can compare them (see "Compare Two Dates" on http://www.w3schools.com/jS/js_obj_date.asp).
I agree with Mayo. If you had access to the date time value and wanted to convert it to a string similar to what you have ("Thursday Sep 10"), you could use this.
Keep it simple; you don't really need a proper date parser to compare your dates. I've got the feeling that you're looking for something quick and dirty:
var now = new Date();
var nowHash = now.getMonth() << 5 + now.getDate();
$("h3").each(function (e) {
var tokens = $(e).html().split(" ");
var hash = [ "Jan", "Feb", ..., "Dec" ].indexOf(tokens[1]) << 5 + tokens[2];
if (hash < nowHash) {
// contract the <ul> that follows
}
});
Month * 32 (or shift 5 bits to left) + day is enough to give you a unique hash of a date that can be compared with other dates.
Mayo is correct about having no quick way. So here is my take on DIY solution.
Basically you extract the date and compare the date yourself.
var aMonths = { "Jan":0, "Feb":1 ..., "Sep":8, ... };
var aToday = new Date();
var aH3Text = .....; // Get the value via jQuery
var aDataElements = aH3Text.split("");
var aMonthIndex = aMonths[aDataElements[1]];
var aDateIndex = aDataElements[2];
var aH3Date = new Date();
aH3Date.setFullYear(2009, aMonthIndex, aDateIndex);
if (aH3Date > today) {
// BEFORE today
} else {
// AFTER today
}
Hope this helps.
Related
I have a date string in the format 28-Dec-2016 04:25 AM and need to convert it to a Date object. For this, I first split the string to get the date and time
cDateStringParts = cdate.split(' ');
Then I get the date and time components
cDateParts = cDateStringParts[0].split('-');
cTimeParts = cDateStringParts[1].split(':');
Then I initialize the Date object like
if(cDateStringParts[2]=='AM'){
cDateObject = new Date(cDateParts[2], convertToNumericMonth(cDateParts[1]), cDateParts[0], cTimeParts[0], cTimeParts[1], 0, 0);
} else {
cDateObject = new Date(cDateParts[2], convertToNumericMonth(cDateParts[1]), cDateParts[0], complaintTimeParts[0] + 12, cTimeParts[1], 0, 0);
}
where convertToNumericMonth() is a function which converts Jan-Dec to 0-11.But I do not get the correct values when I check cDateObject.getDate()/getMonth()/getYear(). The result is 2017/12/29.
What am I doing wrong? If I try to do alert(cdate,' ',cDateObject.getFullYear() I get this:
One issue is how 12hr time is converted to 24hr time. The date parts are strings, so for "03:45 PM" the following:
complaintTimeParts[0] + 12
will return "0312". Also, "12:00 AM" should have the hours set to 0, but your code will set the hours to 12.
The hours can be converted to 24hr time by converting to a number first, converting 12am to 0 and then adding 12 if it's PM. Also simpler if done separately from the rest of the calculation:
var hr = cTimeParts[0] % 12 + (cDateStringParts[2]=='AM'? 0 : 12);
Here the mod operator % will convert cTimeParts[0] to a number. Now the function can be:
function dateParse(cdate) {
var cDateStringParts = cdate.split(' ');
var cDateParts = cDateStringParts[0].split('-');
var cTimeParts = cDateStringParts[1].split(':');
var hr = cTimeParts[0] % 12 + (cDateStringParts[2]=='AM'? 0 : 12);
return new Date(cDateParts[2], convertToNumericMonth(cDateParts[1]),
cDateParts[0], hr, cTimeParts[1]);
}
function convertToNumericMonth(month) {
return {Jan:0,Feb:1,Mar:2,Apr:3,May:4,Jun:5,Jul:6,
Aug:7,Sep:8,Oct:9,Nov:10,Dec:11}[month];
}
console.log(dateParse('28-Dec-2016 04:25 AM').toString());
console.log(dateParse('28-Dec-2016 04:25 PM').toString());
Lastly, missing parts are set to 0 (or 1 for the date) so they don't need to be included.
This link might be a solution for your issue.
you cannot actually rely on the date parsing because, it is dependent on multiple factors like time zones, daylight saving etc.
you could also check your device's time zone and time settings because, the browser uses system data for parsing date.
i have checked the same logic on my browser and it worked fine for me.
here is the example.
if it is working this way, the issue would be that the values calculated by cDateParts is generating different values(very less possibility).
hope this would help you.
This question already has answers here:
Convert dd-mm-yyyy string to date
(15 answers)
Closed 9 years ago.
I want to get day from date. Suppose my date is 03-08-2013 it is in d-mm-yyyy format so I just want to get dand that is 03 from above date so I try this code but it does not work
Note
I want to do it without including any js
var date = '08-03-2013';
var d = new Date(date);
alert(d.getDate());
// 2nd way
alert(date.getDate());
it alert NaN. What is missing in this code?
here is jsfiddel Link Jsfiddle Link
UPDATE
Date parsing in JS (and many languages, for that matter) is problematic because when the input is a date string, it's fairly ambiguous what piece of data is what. For example, using your date (August 3, 2013) it could be represented as
03-08-2013 (dd-mm-yyyy)
08-03-2013 (mm-dd-yyyy)
However, given just the date string, there's no way to tell if the date is actually August 3, 2013 or March 8, 2013.
You should pass your date values independently to guarantee the date is correctly parsed:
var
str = '08-03-2013',
parts = str.split('-'),
year = parseInt(parts[2], 10),
month = parseInt(parts[1], 10) - 1, // NB: month is zero-based!
day = parseInt(parts[0], 10),
date = new Date(year, month, day);
alert(date.getDate()); // yields 3
MDN documentation for Date
You can't know the regional settings of your visitors.
If you know the format of the string is always d-mm-yyyy then just parse the value yourself:
function GetDay(rawValue) {
var parts = rawValue.split("-");
if (parts.length === 3) {
var day = parseInt(parts[0], 10);
if (!isNaN(day))
return day;
}
alert("invalid date format");
return null;
}
Live test case.
Use moment.js. It's parsing ability is much more flexible than the Date class.
var m = moment('03-08-2013','DD-MM-YYYY');
var dayOfMonth = m.date();
Use this it that which you want..
var date = '08-03-2013';
date=date.replace(/([0-9]{2})\-([0-9]{2})\-([0-9]{4})/g, '$3-$2-$1');
var d = new Date(date);
alert(d.getDate());
Thanks
I have to say, I am not an expert with Javascript dates.. at all! I have looked at DateJS for instance, however my problem is not just a simple date conversion (or maybe it should be!).
Quick background:
I have a service call which returns some JSON data that include the dreaded Epoch style date from WCF/REST (I can't use Webapi at the moment - which would give me native JSON.NET?).
So a date examlple from the JSON object is:
StartDate: "/Date(1343378404560+0100)/"
Now, the JSON returned from my call has more information that I need for my Wijmo event calendar object, so I thought ok, will create a Javascript function/model for my Wijmo event object, and use jQuery MAP function to select only the fields I need.
My Javascript event model looks like this:
function wijmoEventModel(in_id, in_calendar, in_subject, in_location, in_start, in_end, in_description, in_colour, in_allday, in_tag) {
this._id = in_id;
this._calendar = in_calendar;
this._subject = in_subject;
this._location = in_location;
this._start = jsonDate(in_start);
this._end = jsonDate(in_end);
this._description = in_description;
this._colour = in_colour;
this._allday = in_allday;
this._tag = in_tag;
// Public Properties/Methods
return {
id: this.id,
calendar: this._calendar,
subject: this._subject,
location: this._location,
start: this._start,
end: this._end,
description: this._description,
color: this._colour,
allday: this._allday,
tag: this._tag
}
};
So, I have another little function that uses the jQuery MAP function as so:
function returnWijmoCalendarObject(diaryEventData) {
// Using jQuery map, reduce our raw event data down to only the required wijmo calendar items
var _calobj = $.map(diaryEventData, function (fld) {
return new wijmoEventModel(fld.ID, fld.ResourceCalendarID, fld.EventTitle, fld.Location, fld.StartDate, fld.EndDate, fld.Description, fld.ResourceColour, fld.AllDay);
});
return {
calendardata: _calobj
}
};
SO the above function just selects the required fields from my original full JSON return, and uses my Javascript function/model to return a new "calendardata" JSON object which I can use with my Wijmo event calendar..
There is one more small function which converts the Epoch style date "/Date(1343378404560+0100)/"
into (I think!) a real Javascript Date object.. like this:
function jsonDate(rawDate) {
var d = new Date();
d.setMilliseconds = parseInt(rawDate.substr(6));
return d;
}
So the above little function of course is used in the first code block above to hopefully convert that Epoch style original date into a Javascript Date.
SO MY QUESTION/PROBLEM IS:
The model above, and jQuery map function works well, I get a subset JSON object of exactly the structure I need, however the dates returned (wijmoEventModel.start & end) don't come back as a Javascript Date object?? even though debuging in that wijmoEventModel definitely has the dates as JS date objects??
Obviously I am missing/not understanding some vital and fundamental aspects here!!!
PLEASE! if anyone can help as this is driving me crazy...
David.
In the jsonDate function, the setMilliseconds property of d (not d itself) will be a date, which you could call from wijmoEventModel.start.d. You actually want var d = new Date(parseInt(rawDate.substr(6))). (Or do you want var d = new Date(parseInt(rawDate.split('+')[0]))?)
Setting milliseconds only sets the milliseconds part of a date, it doesn't set the date from an epoch.
At the heart of a javascript date object is a number of milliseconds since 1970-01-01 00:00:00 in UTC. So if the "time since epoch" that you have is the same, if you convert it to a number you can do:
var d = new Date( Number(millisecondsSinceEpoch) );
See ECMA-262 15.9.3.2
This will create a date object in the local timezone based on the "time since epoch" in UTC. So in different time zones it will show a different time that represent the same instant in UTC.
e.g.
var millisecondsSinceEpoch = '1343378404560';
alert( new Date(Number(millisecondsSinceEpoch))); //Fri Jul 27 2012 18:40:04 GMT+1000 (EST)
The time in the OP is '1343378404560+0100' which implies an offset that I'll assume is hhmm. So that needs to be subtracted from the number before passing it to Date:
var s = '1343378404560+0100';
var t = s.split('+')[1];
if (t) {
t = t.substring(0,2)*3600 + t.substring(2)*60;
} else {
t = 0;
}
var d = new Date(parseInt(s) - t * 1000); // Fri Jul 27 2012 17:40:04 GMT+1000 (EST)
Edit
The above assumes a sign of "+", the string should be split on either "+" or "-", then the sign detected and applied later, e.g.
var t = s.split(/[-+]/)[1];
After setting the value of t, apply the sign:
t *= /-/.test(s)? -1000 : 1000;
var d = new Date(parseInt(s) - t);
Or some variation of the above.
This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Closed 5 years ago.
Having this string 30/11/2011. I want to convert it to date object.
Do I need to use :
Date d = new Date(2011,11,30); /* months 1..12? */
or
Date d = new Date(2011,10,30); /* months 0..11? */
?
var d = new Date(2011,10,30);
as months are indexed from 0 in js.
You definitely want to use the second expression since months in JS are enumerated from 0.
Also you may use Date.parse method, but it uses different date format:
var timestamp = Date.parse("11/30/2011");
var dateObject = new Date(timestamp);
The syntax is as follows:
new Date(year, month [, day, hour, minute, second, millisecond ])
so
Date d = new Date(2011,10,30);
is correct; day, hour, minute, second, millisecond are optional.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
There are multiple methods of creating date as discussed above. I would not repeat same stuff. Here is small method to convert String to Date in Java Script if that is what you are looking for,
function compareDate(str1){
// str1 format should be dd/mm/yyyy. Separator can be anything e.g. / or -. It wont effect
var dt1 = parseInt(str1.substring(0,2));
var mon1 = parseInt(str1.substring(3,5));
var yr1 = parseInt(str1.substring(6,10));
var date1 = new Date(yr1, mon1-1, dt1);
return date1;
}
Very simple:
var dt=new Date("2011/11/30");
Date should be in ISO format yyyy/MM/dd.
First extract the string like this
var dateString = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
Then,
var d = new Date( dateString[3], dateString[2]-1, dateString[1] );
Always, for any issue regarding the JavaScript spec in practical, I will highly recommend the Mozilla Developer Network, and their JavaScript reference.
As it states in the topic of the Date object about the argument variant you use:
new Date(year, month, day [, hour, minute, second, millisecond ])
And about the months parameter:
month Integer value representing the month, beginning with 0 for January to 11 for December.
Clearly, then, you should use the month number 10 for November.
P.S.: The reason why I recommend the MDN is the correctness, good explanation of things, examples, and browser compatibility chart.
I can't believe javascript isn't more consistent with parsing dates. And I hear the default when there is no timezone is gonna change from UTC to local -- hope the web is prepared ;)
I prefer to let Javascript do the heavy lifting when it comes to parsing dates. However it would be nice to handle the local timezone issue fairly transparently. With both of these things in mind, here is a function to do it with the current status quo -- and when Javascript changes it will still work but then can be removed (with a little time for people to catch up with older browsers/nodejs of course).
function strToDate(dateStr)
{
var dateTry = new Date(dateStr);
if (!dateTry.getTime())
{
throw new Exception("Bad Date! dateStr: " + dateStr);
}
var tz = dateStr.trim().match(/(Z)|([+-](\d{2})\:?(\d{2}))$/);
if (!tz)
{
var newTzOffset = dateTry.getTimezoneOffset() / 60;
var newSignStr = (newTzOffset >= 0) ? '-' : '+';
var newTz = newSignStr + ('0' + Math.abs(newTzOffset)).slice(-2) + ':00';
dateStr = dateStr.trim() + newTz;
dateTry = new Date(dateStr);
if (!dateTry.getTime())
{
throw new Exception("Bad Date! dateStr: " + dateStr);
}
}
return dateTry;
}
We need a date object regardless; so createone. If there is a timezone, we are done. Otherwise, create a local timezone string using the +hh:mm format (more accepted than +hhmm).
I noticed Date.Parse can't handle only 2 digits dates.
Say I have this
mm/dd/yy = 7/11/20
Date parse will think it is = 7/11/1920. Can you set it to use the year two thousand? Like it's kinda weird I got the jquery u.i date picker and if you type in 7/11/20 it will figure out 2020.
So it would be nice if Date.parse could keep up I rather have them both not know what is going on or both know what is going on then have one that knows and one that does not know.
Not that I'm aware of. But you can always adjust the year:
YourDate="7/11/20";
DateObj=new Date(YourDate.replace(/(\d\d)$/,"20$1"));
alert(DateObj);
This code in action.
Edit: The following code will handle both full and short years:
YourDate="7/11/2020";
DateObj=new Date(YourDate.replace(/\/(\d\d)$/,"/20$1"));
alert(DateObj);
This code in action.
So your question is whether you can change the way Date.parse works so that low-numbered two-digit dates are interpreted as dates after the year 2000?
Yes, it can be done, simply shadow Date.parse with your own parse function.
// don't do this!
Date.parse = function (str) { /* your parse routine here */ }
Of course, it's generally a very bad idea to shadow properties (including 'methods' aka function properties) of host objects, because it will cause incorrect behavior in other scripts that expect those properties to work a certain way.
It's also a bad idea to use two digit dates, but that might be beyond your control. If it's not beyond your control, I'd advise to just forget 2-digit dates and use the full year value instead.
Here is my solution:
function parseDate(stringValue)
{
var date = new Date(stringValue);
if (!isNaN(date.getTime()))
{
// if they typed the year in full then the parsed date will have the correct year,
// if they only typed 2 digits, add 100 years to it so that it gets translated to this century
if (stringValue.indexOf(date.getFullYear()) == -1)
{
date.setFullYear(date.getFullYear() + 100);
}
return date;
}
else
{
return null;
}
}
How about this?
var date = '7/11/20';
var idx = date.lastIndexOf('/') + 1;
date = date.substr(0,idx) + '20' + date.substr(idx);
var result = Date.parse(date);
alert(result);
or this version that will test for a YYYY format first.
var date = '7/11/2020';
var idx = date.lastIndexOf('/') + 1;
if(date.substr(idx).length < 4) {
date = date.substr(0,idx) + '20' + date.substr(idx);
}
var result = Date.parse(date);
alert(new Date(result));