Formatting a JSON Date with javascript - javascript

I am returning a JSON object from my web service method. The object has some dates in it and so the generated JSON is like the following:
{"d": [
{"PeriodID":8,"Period":"072011","BeginDate":"\/Date(1294268400000)\/"},
{"PeriodID":2,"Period":"052011","BeginDate":"\/Date(1293836400000)\/"}
]}
I am trying to convert this data in a string to be added as <option> elements in an HTML select. This is my code:
var rtypes = data.d;
$.each(rtypes, function (key, value) {
var text = value.Period + " - " + "from " + eval(value.BeginDate.slice(1, -1));
var option = $("<option></option>").attr("value", value.PeriodID).text(text);
$('#rpCombo').append(option);
});
Now the questions:
Can I format the date contained in the Period field (e.g. 072011) as a "July 2011"?
How can I convert the result of eval(value.BeginDate.slice(1, -1)) that is for instance something like "Wed July 14......" into something like "14/07/2011"?
Thanks for helping

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/parse
For example
// create 1 of June 2011 from Jun 2011
var period = new Date(Date.parse("1 "+period));
Here is what I think you want
<script>
var months = ["Jan","Feb","Mar","Apr","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
var result = {"d": [
{"PeriodID":8,"Period":"072011","BeginDate":1294268400000},
{"PeriodID":2,"Period":"052011","BeginDate":1293836400000}
]}
var aPeriod, period, periodMM, periodYYYY, periodText, beginDate, beginMM, beginDD;
for (var i=0,n=result.d.length;i<n;i++) {
aPeriod = result.d[i];
// period = new Date(aPeriod.Period.slice(2),aPeriod.Period.slice(0,2)-1,1,0,0,0);
// periodText = months[period.getMonth()]+" "+period.getFullYear();
periodMM = parseInt(aPeriod.Period.slice(0,2),10);
periodYYYY = aPeriod.Period.slice(2);
periodText = months[periodMM]+" "+periodYYYY;
beginDate = new Date(aPeriod.BeginDate);
beginDD = beginDate.getDate();
if (beginDD<10) beginDD="0"+beginDD;
beginMM = beginDate.getMonth()+1;
if (beginMM<10) beginMM="0"+beginMM;
periodText += " "+beginDD+"/"+beginMM+"/"+beginDate.getFullYear();
alert(periodText)
}
</script>

Not sure on the scale of your project, but I was doing a lot with dates recently and benefitted by implementing javascript extensions on the javascript Date object. This will make your life soooo much easier as it has for me and will take care of the above scenario and then some.
There is a very good article here: Javascript/Json Date Parsing
I did need to tweak it a little, but no looking back since implementing this approach.

Related

How to convert 112889 (mmddyy) to 11/28/89 or 11/28/1989

How do we convert this unformatted date of 112889 (mmddyy) to specific format like 11/28/89?
console.log(new Date('112889'))
// I got this: Sat Jan 01 112889 00:00:00 GMT+0800
I have searched anywhere in google concerning this but found none specific answers.
Reference searches:
https://forums.asp.net/t/1987249.aspx?How+can+i+convert+Date+1365715800000+format+to+MM+dd+yyyy
Convert number into date using javascript
Im also thinking about momentjs formatting but couldn't find any doc about this or did i only missed it
Using the momentjs library you can specify what format your input string will come i.e. MMDDYY in this case.
var d = new moment("112889", "MMDDYY");
document.getElementById('dated').innerText = d.format('MM/DD/YYYY');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<div id="dated"></div>
Please have a look moment.js library. try this code
var date = moment('112889',"MMDDYY").format('MM/DD/YY');
console.log(data);
If you don't want to use a library and if you know that your input is always going to be of mmddyy format, you can do something like this:
var str = '112889';
var arr = str.match(/.{1,2}/g); // Splits string into 2 character chunks
var d = new Date(arr[2],arr[0],arr[1]);
console.log(d);
But this is quite not correct since if you give a string like 112804, JS (or anyone for that matter) will not know if it is 1904 or 2004 and it'll pick up 1904. In that case, you should specify explicitly:
var str = '112896';
var arr = str.match(/.{1,2}/g); // Splits string into 2 character chunks
var d = new Date(arr[2], arr[0], arr[1]); // new Date(yy,mm,dd);
var presentYear = Number((new Date()).getFullYear());
var dateYear = Number(d.getFullYear());
if (presentYear >= dateYear + 100) { // If adding 100 to year makes it greater than present year, then move to 2000s
d = new Date('20' + arr[2], arr[0], arr[1]);
}
console.log(d);

Google forms to calendar event issues with date format

So I have a very simple form that takes 3 inputs, a title, start and end date. I have tried to use a simple script to produce a calendar event. this can be seen below.
function onFormSubmit(e) {
var title = e.values[1];
var start_time = new Date(e.values[2]);
var end_time = new Date(e.values[3]);
CalendarApp.createEvent(title, start_time, end_time);
}
The issue I have is that as the date string is UK format (e.g. 05/12/2016 12:00:00) it is logging the events as 12th May as opposed to 5th December.
I am new to all of this so am looking for an elegant and simple solution I understand, not just to copy code I don't.
Thanks.
function convertUKDateToUSDate(date) {
const arr = date.split('/');
const temp = arr[0];
arr[0] = arr[1];
arr[1] = temp;
return arr.join('/');
}
will convert a date string with the prefix "DD/MM/" into "MM/DD/YYYY" format. Split turns the string into an array like ["DD", "MM", "YYYY HH:MM:SS"] and then the temporary variable is used to swap the "MM" and "DD" before the array entries are joined back together with the same character that was used to split them. You'll end up with a final onFormSubmit(e) like this:
function onFormSubmit(e) {
var title = e.values[1];
var start_time = new Date(convertUKDateToUSDate(e.values[2]));
var end_time = new Date(convertUKDateToUSDate(e.values[3]));
CalendarApp.createEvent(title, start_time, end_time);
}
Obviously I'm assuming e.values[2] and e.values[3] are strings. If they're Date objects already (or if you just want a shorter solution), then consider using the Moment.js (the premier Date object library) format function to convert between the formats. Normally I'd recommend using Moment anyways but you said you wanted something you could understand instead of copy.

Set array based on specific dates

Im looking to be able to set an arrays contents based on specific dates i.e.
if the date is the 25/12 then the array would look like the following
var compliments = [
'Happy Xmas!',
'Hope you been a good boy',
];
I would like to be able to do this over various dates and also have a default for the non special dates.
I am aware you would need to use the date function in javascript however I'm not experienced enough to work this out.
You can index your compliments with a date string.Try something like this.
var today = new Date(),
today_string = today.getMonth() + "-" + today.getDate();
compliments = {
"12-25": [
'Happy Xmas!',
'Hope you been a good boy'
],
"1-1": ["Happy new year!"],
"Default": ["Happy today ¬¬"]
};
console.log(compliments[today_string] || compliments["default"]]);
Use objects line array.
var compliments = {}
compliments['12/05'] = ['bla1', 'bla2'];
compliments['13/06'] = ['bla3', 'bla4'];
you can access them like this:
alert(compliments['12/05'][0] + compliments['12/05'][1]);

Convert RFC 3339 date to dd-M-yyyy in javascript or jQuery?

I have a large table returning data from solr, I can't do anything server side so I need to use client side javascript and the date format emitted is:
yyyy-mm-ddThh:mm:ssZ
Lovely. I want it to display as:
dd-M-yyyy (or 21-Jan-2011, for example)
Each date is in a td with a class of "formatdate". I thought something like this (below) would work, sitting inside a
$(document).ready(function()
and format everything "automagically", but no such luck;
$('.formatdate').each(function() {
var date = document.getElementByClassName('formatdate');
$(".formatdate").innerHTML = new Date(date);
});
Any ideas?
EDIT: The other side of this is, inserting this
"mRender": function(date, type, full) { return new Date(date).toDateString(); }
into datatables returns "Fri Nov 2 2012", but then I have zero formatting options - it really has to be "02-Nov-2012"... Thanks again!
Did you mean something like this? Fiddle.
$(".formatdate").each(function () {
var $this = $(this),
date = $this.html();
$this.html(new Date(date));
});
The problem is that you are basically saying this:
For each .formatdate...
Get the collection of .formatdate elements
Create a date from them (???)
Put that date in all .formatdate elements.
Needless to say, it's not what you intended!
Try this:
var months = "JanFebMarAprMayJunJulAugSepOctNovDec";
$(".formatdate").each(function() {
var dateparts = this.firstChild.nodeValue.match(/(\d{4})-(\d\d)-(\d\d)/);
this.firstChild.nodeValue =
dateparts[2] + "-"
+ months.substr((dateparts[1]-1)*3,3) + "-"
+ dateparts[0];
});

Object Oriented JavaScript: How would you go about this?

As I've gotten to know JS better, I've moved from a procedural style to semi-OO (don't ask me what I mean by that: a mess basically!) but now I want to start using it properly. OO appeals to my coding-brain.
However, I'm trying to develop a library of school weeks, and I'm not sure how I'd best go about it.
If I was to simply use an array of weeks, they would look something like this:
WeeksArray[36].StartDate = "2011-09-05";
WeeksArray[36].EndDateSchool = "2011-09-09";
WeeksArray[36].EndDateProper = "2011-09-11";
WeeksArray[36].JSDate = new Date ( 2011, 8, 05 );
WeeksArray[36].Type = "1";
WeeksArray[36].Label = "Week 36: 5th Sept 2011";
Key: Week number according to School Calendar
StartDate / EndDate: MySQL-compatible date ranges
JSDate: JS date object of start of week
Type: school timetable, week 1 or 2
Label: human-readable label indicating start of week
I would like this library to be accessible by other scripts, so that they can load an Array or Object containing all of the weeks in the school calendar. I'd imagine, for instance, one of my scripts producing a drop-down menu from this information, which displays "Week 36: 5th Sept 2011" and when clicked upon sends a request to my PHP script & SQL database then filters the information on screen accordingly. NOTE: I don't need help with the implementation of the latter, it's just an example for context.
I started coding as follows:
var LEAP = {}
LEAP.Schedule = {
init: function() {
this.setWeeks();
}
setWeeks: function() {
var WeeksArray = [];
But the more I look at it, the less correct it feels!
Should I be creating "Week" objects, then a container for them which has a method to return all of the Week objects? I've been reading the OOP chapter in "Pro JavaScript Techniques" by John Resig, but truth be told I don't fully understand it. This feels like the right approach, but an Object within an Object is hurting my head.
The final outcome should be that I include this script on one of my pages, then can use something like var WeeksArray = LEAP.Schedule.getWeeks();, but even then I'm not sure that's realistic?
I'm rather confused...! :D Any help on the subject would be hugely appreciated.
setWeeks: function(){
var WeeksArray = []; //This variable is private, which is probably not your desired result.
}
^ That doesn't work, see comment.
I'd recommend something like this:
External file:
var LEAP = {};
LEAP.Schedule = function(){//init
//all events which should only occur once should be called here
//Create the initial objects, e.g.
this.weeks = [];
this.calculateWeeks();
}
LEAP.Schedule.protoype.calculateWeeks = function(){
for (var i=0; i<52; i++){
this.weeks.push(Math.random()); //For the sake of the example ;)
}
}
LEAP.Schedule.prototype.getWeeks = function(){
return this.weeks;
}
Main file:
var Scheduleobject = new LEAP.Schedule();
var weeks = Scheduleobject.getWeeks();
This feels like a very natural OOP approach, to me.
You can even change the LEAP.Schedule function such that it returns the Weeks array immediately, dependent on the situation.
EDIT
An example of a week class:
LEAP.Schedule.week = function(n_year, n_month, n_day, n_week){
//add code to validate the input
//...
//finished validating, processing:
this.year = n_year;
this.month = n_month;
this.day = n_day;
this.week = n_week;
}
LEAP.Schedule.week.protoype.getStartDate = function(){
return year + "-" + pad(month) + "-" + pad(day);
}
//LEAP.Schedule.week.prototype.*Date are defined in a similar way
//The "EndDateSchool" and "EndDateProper" variables always follow the same pattern. Reduce the number of unnecessary variables by calculating these variables in the prototype function.
LEAP.Schedule.week.prototype.getLabel = function(){
return "week" + this.week + ": " + this.day + (day==1||day==21||day==31?"st":day==2||day==22?"nd":day==3||day==23?"rd":"th") + " " + ["jan", "feb", "mar", "etc"][this.month-1] + " " + this.year;
}
function pad(n){return n>9?n:"0"+n}//a simple function to add a zero for your specific cases.
The week class can be called in this way:
var week = new Schedule.Week(2011, 8, 5, 36); //or this.Week(2011, 8, 5, 36) from the contex of the class.
var startDate = week.getStartDate(); //example`
Following up on my comment.
You might not ever need formal week objects. It might be enough to simply store which weeks are which type, and a formula for converting the number to a date. So your Calendar or Schedule object might have a property indicating the absolute day that week number 1 starts, and an array of week types in order. Then when getWeeks() is called, it can start at week 1 and build an array of the necessary weeks, which could be formal objects, or could simply be associative arrays:
weeks = [];
for (var i = 0; i < this.week_types.length; i++){
weeks[i] = {
"StartDate": this.get_start_date(i),
"JSDate": this.get_js_date(i),
..., //The rest of the properties
"type": this.week_types[i],
"Label": this.get_label(i)
}
Hopefully that starts you on the right track, I'm happy to help if I can provide further clarification.

Categories

Resources