Change order in a date with javascript - javascript

If I have a date like 8/9/2010 in a textbox, how can I easiest set a variable to the value 201098?
Thanks in advance.

var date = "8/9/2010";
var result = date.split('/').reverse().join('');
EXAMPLE: http://jsfiddle.net/hX357/
To add leading zeros to the month and day (when needed) you could do this:
var date = "8/9/2010";
var result = date.split('/');
for( var i = 2; i--; )
result[i] = ("0" + result[i]).slice(-2);
result = result.reverse().join('');
EXAMPLE: http://jsfiddle.net/hX357/2/

I would recommend using Datejs to process your dates.
You can do something like
date.toString("yyyyMMdd");
to get the date in the format you want

Using regex:
"8/9/2010".replace(/([0-9]+)\/([0-9]+)\/([0-9]+)/,"$3$2$1")

Do a split on '/', take the last element and make it the first of a new string, the middle element becomes the middle element of the new string, and the first element becomes the last element of a new string.
It would be like this:
myString = document.getElementById('date_textbox').value;
var mySplitResult = myString.split("\");
var newString = mySplitResult[2] + mySplitResult[1] + mySplitResult[0];
This is basically the idea I think you are going for.
-Brian J. Stinar-
Dang, it looks like I was beaten to the punch...

Or you can use the built-in JavaScript Date class:
function processDate(dStr) {
var d = new Date(dStr);
return d.getFullYear() + (d.getMonth() + 1) + d.getDate();
}
processDate("8/9/2010");
Easiest to manage and debug, certainly.

Related

Convert Date in to custom format in javascript

I have a Date format like this
2014-11-18T20:50:01.462Z
I need to convert to the custom format like "20:50 2014-18-11" using Javascript date function
I need result like
20:50 2014-18-11
How to get this , Thanks in Advance :)
Assuming you're able to include new libraries on your project, I'd highly recommend moment.js (MIT license) instead of writing this yourself. It solves problems like zero padding etc. for you.
Example
<script src="http://momentjs.com/downloads/moment.min.js"></script>
<script>
// Use an existing date object
var date = new Date("2014-11-18T20:50:01.462Z");
console.log(moment(date).format('HH:mm YYYY-DD-MM'));
// or use string directly
console.log(moment.utc("2014-11-18T20:50:01.462Z").format('HH:mm YYYY-DD-MM'));
</script>
Note by default moment will use your current timezone for output, this can be overridden using the zone() function
console.log(moment.utc("2014-11-18T20:50:01.462Z").zone(0).format('HH:mm YYYY-DD-MM'));
console.log(moment.utc("2014-11-18T20:50:01.462Z").zone('UTC+05:30').format('HH:mm YYYY-DD-MM'));
Output
20:50 2014-18-11
Try moment js its very nice plugin to play around dates and times
so all you need to do is import moment js and put this line in your js code
using moment.js will also help you in future for your code
moment.utc("2014-11-18T20:50:01.462Z").format("HH:mm YYYY-DD-MM")
Use this Demo JsFiddler
var d = new Date,
dformat = [ d.getHours().padLeft(), d.getMinutes().padLeft()].join(':')
+ ' ' +
[d.getFullYear(), d.getDate().padLeft(), (d.getMonth()+1).padLeft()].join('-')
;
Date.prototype._padding = function(v, w) {
var f = "0000" + v;
return ("0000" + v).substr(f.length-w, f.length)
}
Date.prototype.MyDateString = function() {
return this._padding(this.getUTCHours(), 2) + ":" + this._padding(this.getUTCMinutes(), 2) + " " + this.getUTCFullYear() + "-" + this._padding(this.getUTCDate(), 2) + "-" + this._padding((this.getUTCMonth() + 1), 2);
}
console.log(new Date('2014-11-18T20:50:01.462Z').MyDateString())
console.log(new Date('2014-11-08T02:05:01.462Z').MyDateString())
getUTCMonth return 10, as the month is 0 based.

Format Date in Javascript/JQuery as Single Digit Day

Currently, I am pulling in a json feed from our calendar. It brings back the date in the yyyy/mm/dd format... I know I can overwrite this format by using javascript but how would I do this? I need the output to only be the "dd" not the month nor the year.
I would also like single digit days to show up as i.e. "1","2","3","4" and of course dbl digits to show up as usual "10", "11", "12", etc. Any ideas on how I could achieve this reformatting of the date via javascript/jquery?
You can use a Date object
var theDate = new Date(dateString);
var theDay = parseInt(theDate.getDate(), 10);
Alternatively, if you don't want to use the object and can expect the same string back each time:
var theDay = parseInt(dateString.split('/')[2], 10);
This code should do it . . .
var jsonDate = <...reference to the JSON date value...>;
var dayValue = jsonDate.split("/")[2].replace(/0(.)/, "$1");
You've already got a string value, so might as well just manipulate it as a string.
jsonDate.split("/")[2] splits up the full date and then takes the third item from the resulting array (i.e., the day value)
.replace(/^0(.)$/, "$1") will trim off the "0", if it finds it in the first position of the "day" string
Then you just use dayValue wherever you need to use it. :)
UPDATE:
Based on the comments below, try using this as your code:
var listingEl = $('<div class="eventListings" title="' + item.event.title + '" />');
var dateEl = $('<div class="mdate">' + dayValue + '</div>');
var linkEl = $('<a href="' + item.event.localist_url + '" />');
var titleEl = $('<div class="mcTitle">' + item.event.title + '</div>');
linkEl.append(titleEl);
listingEl.append(dateEl);
listingEl.append(linkEl);
$('#localistTitle').append(listingEl);
UPDATE 2:
There was something not working in your code (I think the main issues was how you were using .appendTo()). I split it out into a multi-step process and used .append() instead. It worked correctly when I tested it locally.

ISO duration with Java script

I apologize for the question because I have already posted a similar question, but I would like to know how I can do the following conversion:
PT11H9M38.7876754S
I want to disable seconds and only show hour and minutes 11:09
When I have time displays minutes from 1 to 9, I want to add a 0 in front of number
Tnx in advice...
You could try this:
var str = 'PT11H9M38.7876754S'
match = str.match(/(\d*)H(\d*)M/),
formatted = match[1] + ':' + (!match[2][1] ? 0 + match[2] : match[2]);
console.log(formatted); // => 11:09
"PT11H9M38.78767545".replace(/PT(\d+)H(\d+)M.*/,function(m,a,b) {return a+":"+(b.length<2?"0":"")+b;});
One-liner :p
Since all the nice RegExp stuff is above here is a third solution a bit more expensive in terms of parsing but you may be looking for something different.
You can use the split function to parse the string and extract the portions that you need.
var pt="PT11H9M38.7876754S";
function showtime(s){
var time = s.split('.');
var hours = time[0].split('T')[1].split('H')[0];
var minutes = time[0].split('H')[1].split('M')[0];
return digitize(hours) + ":" + digitize(minutes)
}
function digitize(i){
return (i>9) ? i : "0" + i;
}
alert(showtime(pt)); // 11:09

jquery load append datepicker function

I have the following function that produces numbered input fields with ids and names of the current timestamp they're were created. I'm trying to attach a datepicker to each one created, hence the unique/timestamp id's.
Can anybody suggest a way for me to go about doing this?
I believe the datepicker function needs to be produced under each input field created but I don't know how to produce a JavaScript function with JavaScript. I'm thinking maybe I can use jQuery's load() function and call a PHP script that produces a unique function and loads it into a div. Is that the best way to tackle this? Thanks!
<script>
var number = 0;
var num;
$('#add_date').click(function(event) {
number++;
var d=new Date();
var year = d.getFullYear();
var day = d.getDate();
var month = d.getMonth() + 1;
if (month<10){var month = "0"+month;}
if (day<10){var day = "0"+day;}
var fullyear = month+"/"+day+"/"+year;
num = event.timeStamp
$('#box').append( number+". <input type='text' id='" + num + "' name='" + num + "' value='"+ fullyear + "' size='10'/><br><br>");
var idtag = "#"+num;
});
</script>
Why not just set up the datepicker when you create the input?
var picker = $("<input/>", {
type: 'text',
id: num,
name: num,
value: fullyear
}).datepicker();
$('#box').append(number).append(picker);
Also you should make "id" values that look like valid identifiers instead of plain numbers.
Look at #Pointy's answer for an actual solution, he was quicker than me, my answer will not actually solve your problem, I just would like to mention a few points to note.
Try to indent your code properly, so it's easy to read for you after looking at it in a month's time. You might know now what it does exactly, but it will be a pain to figure it out in the long term.
As unlikely as it is, it can't be guaranteed that the same event won't fire twice in the same millisecond, I would avoid using event.timeStamp for generating unique IDs. It's just a personal preference though, it will probably never happen, I just don't like to rely on timers for uniqueness. You have your incrementing number variable already, you should use that, that will definitely be unique.
When writing HTML into a string, I would rather use the proper standard markup. Use ' as your string boundaries and " for your HTML attributes.
Lastly, inside your if(month<10){...} condition, don't redefine the variable you have already defined within your function. It would probably not throw an error or have any negative effect, but we can only thank the current forgiving javascript implementation for that, redefinition should not be allowed in the same scope.
Finally make sure you put all your jQuery initialisation code into the jQuery ready function to make sure the DOM and jQuery itself has fully loaded.
And sorry for the rant... ;)
$(function(){
var number = 0;
$('#add_date').click(function(event) {
number++;
var d=new Date();
var year = d.getFullYear();
var day = d.getDate();
var month = d.getMonth() + 1;
if (month<10) month = "0"+month;
if (day<10) day = "0"+day;
var fullyear = month+"/"+day+"/"+year;
// Insert #Pointy's solution in here...
});
});
You can add a fict
<input type='text' id='" + num + "' name='" + num + "' value='"+ fullyear + "' size='10' class='fake-class'/>
And then, you can load the datepicker object like this:
$('.fake-class').each(function(){
$(this).datepicker();
});
Hope it helps
Just a little correction about the variable num and number, #Pointy was using num and #DarthJDG was using number. Here is the complete code that worked for me
In Script:
var num = 0;
$('#btn').click(function(event) {
<!-- Set the default date to be todays date, can be removed for blank-->
num++;
var d=new Date();
var year = d.getFullYear();
var day = d.getDate();
var month = d.getMonth() + 1;
if (month<10) month = "0"+month;
if (day<10) day = "0"+day;
var fullyear = month+"/"+day+"/"+year;
<!-- End -->
var picker = $("<input/>", {
type: 'text',
id: num,
name: num,
value: fullyear
}).datepicker();
$('#holder').append(num).append(picker);
}
And in the HTML:
<input type="button" id="btn" value="button">
<div id="holder">
</div>

How to convert string to date javascript?

I have this as my date: 1212009 so this should be like 12/1/2009 but I am stuck this as an id field and id fields cannot have dashes in there names.
Now can java-script take this number and re add the slashed in for me or how would I go about doing this?
Thanks
You should have two-digit numbers for the month and day, since "1212009" is ambiguous, could be interpreted as "1/21/2009" or "12/1/2009".
If you add the leading zeros, you know that there will be always 8 digits, so you can do something like this:
var str = "12012009"
var result = str.replace(/(\d{2})(\d{2})(\d{4})/, "$1/$2/$3");
// 12/01/2009
Or
var result = str.match(/(\d{2})(\d{2})(\d{4})/).slice(1).join('/');
// 12/01/2009
Well without leading zeros, it's not possible to make a reliable conversion. It's impossible to know if 1232009 is 1/23/2009 or 12/3/2009 without leading zeros. Also, your example number could be interpreted as 1/21/2009 too.
All you need to do is pass the string into the new date constructor.
Here is a good javascript resource for you to look at.
http://www.javascriptkit.com/jsref/date.shtml
Assuming that you add the leading zeroes to remove the ambiguity, you can format the date like so:
dateString = String(id).match(/(\d{2})(\d{2})(\d{4})/).slice(1).join('/')
Maybe this will help you to get rid of the six or seven numbers long date (most important part is the first part):
var sDate = "1212009";
if(sDate.length == 7){
sDate = sDate.substr(0,2) + "0" + sDate.substr(2);
}
else if(sDate.length == 6){
sDate = "0" + sDate.substr(0,1) + "0" + sDate.substr(1);
}
// This part can be done with Regular Expressions, as shown in other comments
var month = parseInt(sDate.substring(0,2));
var day = parseInt(sDate.substring(2,4));
var year = parseInt(sDate.substring(4));
alert(day + "/" + month + "/" year);
// Will alert 12/1/2009
However,
1232009 will always be 01/23/2009, not 12/03/2009
112009 changes to 1/1/2009
10102009 changes to 10/10/2009

Categories