date string formatting - javascript

The best way to take a string that is formated like...
YYYY-MM-DD
and make it appear like...
MM/DD/YYYY
The reason it is not a javascript date object is because I am working with massive amounts of data and these dates are being pulled from a database.
I see no need to convert it to a date object.

How about:
s.substr(5,2) + '/' + s.substr(8) + '/' + s.substr(0,4)

You can use a regular expression in JavaScript (assuming JS because your question is tagged as such):
var date = "2010-05-09";
var formatted = date.replace(/([0-9]{4})-([0-9]{2})-([0-9]{2})/, "$2/$3/$1")
What I like about this more than using substring is that it seems more apparent what is being done.

If you replace the dashes with slashes it will parse, then you can use the date functions to get the various components (or convert to string using one of the various toString() functions).
var date = new Date( Date.parse( old.replace(/-/g,'/') ) );
alert( date.getMonth() + '/' + date.getDate() + '/' + date.getFullYear() );
This has the advantage of being able to use the date as a date for calculations, not merely doing string formatting. If string formatting is all you need AND your date strings are always valid, then using #Guffa's substr method is probably the best way to handle it.

By brute force you could do something like:
var old = '2010-02-03'.split('-');
var desired = old[1] + '/' + old[2] + '/' + old[0];
Saves the hassle of working with Date object.

Related

Convert date string of 'yymmdd' format to 'MM-DD-YYYY'

Hi I have strings representing dates in the format of 'yymmdd' i.e. '200421' represents 04-21-2020. How can I convert this to a format of 'MM-DD-YYYY' which is commonly used? I'm thinking this should be simple enough to use Date or momentjs, rather than getting creative and using substrings, etc..
I've been playing around with momentjs on http://jsfiddle.net/v9n4pL8s/1/
and have tried var now = moment('200421').format('MM-DD-YYYY');
alert(now);
but it seems to be all trial and error. Anybody have a simple way of doing this? Thanks!
you have to pass the date format as the second argument.
const date = moment('200421', 'YYMMDD').format('MM-DD-YYYY');
console.log(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.2.1/moment.min.js"></script>
var str = '200421';
function format(date) {
return date.slice(2, 4) + '-' + date.slice(4) + '-20' + date.slice(0, 2);
}
format(str); // "04-21-2020"
I know you don't want to use substring but, I think this can be useful.

Convert Date String(yymmdd) to Date Object in JS

I have a date string in "yymmdd" format i want to convert it into date object in JS
the input string is "161208"
I have tried code below
var mydate = new Date(InputDate);
but it says invalid date.
Here is the fiddle
https://jsfiddle.net/4ry0hL4t/
the basic need is that, I have a date string in "yymmdd" format and i have to convert it to different date formats like ("yyyy/mm/dd, yy-mm-dd","yy/mm").
Check my answer.
Basically you first need to give a proper format to your string. You can either do it manually or use moment.js.
stringFormat = moment(dateObject).format("YYYY-MM-DDTHH:mm:ss");
date = new Date(stringFormat);
This is also really helpful to understand how the different string formats are compatible with different browsers.
I'm not sure if this is what you're after?
var s = '161208';
var dt = new Date('20' + s.substring(0, 2) + '-' + s.substring(2, 4) + '-' + s.substring(4));

How to find the duration between dates?

I have the date as 07/24/2012 and the time as 23:59:59 in separate variables. Using moment.js I am trying to find the number of days/hours/minutes between this and the current date.
How can this be done with moment.js?
Assuming $date holds "07/24/2012" and $time holds "23:59:59"...
moment($date + " " + $time, "MM/DD/YYYY HH:mm:ss").fromNow();
The + operator concatenates the strings which form a value that moment can parse directly.
Reference:
Moment parsing
Moment time from now
moment.js doesn't provide a "direct" way to perform this task as fromNow likes to get clever and likes to use humanize; however (using from in the moment.js source as inspiration) we can derive a little solution:
var whence = moment("2040-11-28")
var remaining = moment.duration(whence.diff(moment()))
Then to use/format the duration (sadly, there is no duration.format() available):
var r = remaining
var str = Math.floor(r.asDays()) + "." + r.hours() + ":" + r.minutes() + ":" + r.seconds()
alert(str)
PaulProgrammer's answer provides a nice solution on how how to get the date initially from the two separation values. Alternatively (since Moment.js 2.1.0), the date-time can be obtained through:
var whence = moment(yourDate, "MM/DD/YYYY").add(moment.duration(yourTimeOfDay))

Convert and Read JSON date type in Javascript

I have a date in the form of:
"2012-10-11T00:00:00"
The date is returned from a ASP.NET Webservice as part of a JOSN object. How can I convert this date format to a Javascript date object and also write the date as follows to the screen:
11/10/2012
Thanks
var myDate = new Date("2012-10-11T00:00:00".replace(/T/," "));
var myDateString = myDate.getDate() + "/" + (myDate.getMonth() + 1) + "/" + myDate.getFullYear()
For date conversions I use a plugin
date.js
Be sure to include all the jquery files needed, there is plenty of documentation on how to implement this
If you do not want to use a plugin check this out http://msdn.microsoft.com/en-us/library/ie/ff743760(v=vs.94).aspx
Or this overflow answer

jquery trim leading zeros from date of format 01/02/2010

How do I trim javascript date object returned as 01/26/2012 into 1/26/2012?
it could be applicable for both month or days.
So 01/01/2012 should be trimmed as 1/1/2012.
Regular expression? jquery trim function? I am not sure how to go on this?
var date=date.replace(/^0+/, '');
or
var trimmed = s.replace(/\b(0(?!\b))+/g, "")
For a simple string operation, a RegEx can be used:
date = date.replace(/\b0(?=\d)/g, '')
If it is indeed a date object format it.
Quick example (See it in action):
var today = new Date();
var today_string = (today.getMonth() + 1) + '/' + today.getDate() + '/' + today.getFullYear();
alert(today_string);
Either way, this is not a good use of regular expressions.
Convert to a Date object first.
http://www.w3schools.com/jsref/jsref_obj_date.asp
Javascript doesn't have built-in formatting functions for dates, but there are a lot of simple libraries that serve this need. Personal favorite: http://blog.stevenlevithan.com/archives/date-time-format

Categories

Resources