Javascript Date from 20/11/2010 to November 20th, 2010? - javascript

I have a string value something like the below values
9/21/2010
9/24/2010
And I want to convert those to
September 21nd, 2010
September 24th, 2010
is there an easy way of doing this? Or do I have to do it the hard way?
PS. This is strictly javascript, please don't post jQuery examples.
Thanks!

It depends on what you mean by "the hard way". One way is to split the date into it's components and convert to date (assuming US m/d/y format) and then format the date object how you want:
function toDate(s) {
var bits = s.split('/');
return new Date(bits[2], bits[0] - 1, bits[1]);
}
function addOrdinal(n) {
var ords = ['th','st','nd','rd'];
var o = ('' + (n%10))
if (n > 10 && n < 14) {
return n + 'th';
} else {
return n + (ords[o] || 'th');
}
}
function formatDate(d) {
var months = ['January','February','March','April','May','June',
'July','August','September','October','November','December'];
return months[d.getMonth()] + ' ' + addOrdinal(d.getDate()) + ', ' + d.getFullYear();
}
Another is to just convert the month to its name:
function reFormatDate(s) {
var bits = s.split('/');
var months = [,'January','February','March','April','May','June',
'July','August','September','October','November','December'];
return months[bits[0]] + ' ' + addOrdinal(bits[1]) + ', ' + bits[2];
}
Edit
Added the ordinal to date.

You can create new date by just supplying a string to the Date() constructor.
var date = new Date("9/21/2010");
http://www.w3schools.com/jsref/jsref_obj_date.asp
However, to display the date as a string in a customizable way, you'll need to either do it the hard way or using a library, such as dateJS. Javascript provides a couple of output formats for dates, but none of them is especially customizable.

function niceDate(dateString) {
var m = [,'January','February','March','April','May','June','July',
'August','September','October','November','December'];
var s = ['th','st','nd','rd','th','th','th','th','th','th'];
var d = dateString.split('/');
return(m[d[0]-1] + ' ' + d[1] + s[d[1]>4&&d[1]<20?4:d[1]%10] + ', ' + d[2]);
}

Related

Convert Round-Trip Time Pattern in ES6

I'm trying to convert something like this 2020-10-01T17:00:00.000Z to the correct time something like 06:00:00 PM. Pls see my code below:
const date = "2020-10-01T17:00:00.000Z";
const output = new Date(date).toLocaleTimeString('en-US');
console.log(output);
If you specifically need the time to be in UTC (instead of the local user's timezone), then I think you would need to build your own formatter function to do it, e.g.:
function formatDate(str, includeDate){
const date = new Date(str);
const hours = date.getUTCHours();
let twoDigits = (no) => {
const str = no.toString();
return (str.length === 1 ? '0' + str : str);
};
let strdate = (includeDate ? twoDigits(date.getUTCMonth() + 1) + '/' + twoDigits(date.getUTCDate()) + '/' + twoDigits(date.getUTCFullYear()) + ' ' : '');
if(12 <= hours) {
return strdate + twoDigits(hours === 12 ? 12 : hours - 12) + ':' + twoDigits(date.getUTCMinutes()) + ':' + twoDigits(date.getUTCSeconds()) + ' PM';
} else {
return strdate + twoDigits(hours) + ':' + twoDigits(date.getUTCMinutes()) + ':' + twoDigits(date.getUTCSeconds()) + ' AM';
};
};
console.log(formatDate("2020-10-01T17:00:00.000Z", true));
Here, you are constructing the time string from individual UTC segments. You could alternatively parse the input string using a regex, get the number of hours and then build the string that way.
Edit: updated to optionally also include the date, in US format mm/dd/yyyy.

The .toISOString() results into a date ahead of the current date-Js [duplicate]

Why did this piece of code return tomorrow's date ?
It must return 2013-08-31 and not 2013-09-01 as we are August 31st.
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_toisostring
function myFunction() {
var d = new Date();
var x = document.getElementById("demo");
x.innerHTML = d.toISOString();
}
<p id="demo">Click the button to display the date and time as a string, using the ISO
standard.</p>
<button onclick="myFunction()">Try it</button>
It's in UTC.
If you want to get your local timezone you have to format the date yourself (using getYear() getMonth() etc.) or use some library like date.js that will format the date for you.
With date.js it's pretty simple:
(new Date()).format('yyyy-MM-dd')
edit
As #MattJohnson noted date.js has been abandoned, but you can use alternatives like moment.js.
use:
new Date().toLocaleDateString('pt-br').split( '/' ).reverse( ).join( '-' );
or
(function() {
function pad(number) {
if (number < 10) {
return '0' + number;
}
return number;
}
Date.prototype.toISO1String = function() {
return this.getFullYear() +
'-' + pad(this.getMonth() + 1) +
'-' + pad(this.getDate()) +
'T' + pad(this.getHours()) +
':' + pad(this.getMinutes()) +
':' + pad(this.getSeconds()) +
'.' + (this.getMilliseconds() / 1000).toFixed(3).slice(2, 5) +
'Z';
};
})();
See: mozilla.org toISOString doc
I just modified it
You can simply use Luxon.
DateTime.fromJSDate(new Date(yourDateVariable)).toFormat('yyyy-MM-dd')

How to convert "20120111141311Z" into yyyy-mm-dd hh:mm:ss +/- hh:mm

I am getting date value in format "20120111141311Z".
I want to convert the above value into yyyy-mm-dd hh:mm:ss +/- hh:mm format.
Don't know how to do it. I tried with Date() function, it is giving NaN.
Parsing of date strings using the Date constructor is largely implementation dependent and not reliable. All you want to do is reformat a string, so split it into parts and do that, e.g.:
function formatString(s) {
var b = s.match(/\d\d/g);
if (b) {
return b[0] + b[1] + '-' + b[1] + '-' + b[2] + ' ' +
b[3] + ':' + b[4] + ':' + b[5] + '+0000';
}
}
You can do a similar thing using substring, but match is simpler I think. The timezone is +0000 since you've specified Z. It's not difficult to deal with actual offsets.
I was able to solve the problem using below code
zuluDate: function(value){
if (value) {
var year = value.substring(0,4);
var month = value.substring(4,6);
var date = value.substring(6,8);
var hour = value.substring(8,10);
var min = value.substring(10,12);
var sec = value.substring(12,14);
return new Date(year, month-1, date, hour, min, sec);
}
}
Thanks everyone for posting your answer.

Jquery / Javascript - every date to timestamp

i try to build a function that converts every date to a timestamp.
JS
$(document).ready(function()
{
var date1 = dateParser('Fri, 20 Jan 2012 09:30:02 +0000');
$('body').append('date1 -> '+date1.timeStamp +' / '+date1.isoDate + '<br />');
var date2 = dateParser('2012-01-19T20:34:15+0000');
$('body').append('date2 -> '+date2.timeStamp +' / '+date2.isoDate + '<br />');
});
function ISODateString(d) { function pad(n){ return n<10 ? '0'+n : n }
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
function dateParser(someDate) {
if(typeof someDate == 'string') {
var timeStamp = Date.parse(someDate) / 1000;
var isoDate = ISODateString(new Date( timeStamp*1000 ));
}
if(typeof someDate == 'number') {
var timeStamp = someDate;
var isoDate = ISODateString(new Date( someDate*1000 ));
}
return {"timeStamp": timeStamp, "isoDate": isoDate };
}
example: http://jsfiddle.net/L6uce/6/
The first date works but the second returns NaN / NaN-NaN-NaNTNaN:NaN:NaNZ.
Any ideas? Is there maybe a better (easier) way?
Thanks in advance!
Look here to learn more about ISO:
http://en.wikipedia.org/wiki/ISO_8601
Substitute "+0000" with Z and it works.
"Combining date and time representations to represent a single point in time (time point) is quite simple. It is in the format of T where the time designator [T] is used to show the start of the time component of the representation. Both the date and time components of the time point are any proper representations of date and time specified by the standard. For example, "2007-04-05T14:30" uses the extended formats for date and time [YYYY]-[MM]-[DD]T[hh]:[mm], while "20090621T0545Z" uses the basic formats [YYYY][MM][DD]T[hh][mm]Z."

Parsing the date in MM/DD/YY format

I get the response for the Date in this format while showing in the text box, how do i covert it to MM/DD/YYYY and Again re covert it to back to this format while sending
/Date(1306348200000)/
function dateToString(date) {
return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getYear();
}
function dateFromString(str) {
return new Date(str);
}
Note, that month begins from 0.
To convert the regExp-like string to a real Date Object you could use:
var dateNum = Number('/Date(1306348200000)/'.replace(/[^0-9]/g,''))
, dat = new Date(dateNum); //=>Date {Wed May 25 2011 20:30:00 GMT+0200}
To display formatted dates I use my own small library, which may be of use to you.
var s = '/Date(1306348200000)/';
// convert to javascript date
var date = new Date(parseInt(s.substr(6, 13))); // removes /Date( & )/
// format the date
function pad(n) { return n < 10 ? '0' + n : n; } // leading zeros
var ddmmyy = pad(date.getDate()) + '/' + pad(date.getMonth() + 1) + '/' + date.getFullYear().toString().substr(2);
// convert back
s = '/Date(' + date.getTime() + ')/';
here you can find everything regarding javascript dates http://www.w3schools.com/js/js_obj_date.asp

Categories

Resources