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.
Related
I have getting a dateformat like '23.10.2017'. I need to format this in to
'10/23/2017'
I just tried
var crDate='23.10.2017';
var newDateF=new Date(crdate).toUTCString();
but it showing InvalidDate
can anyone help to change the format.
Thanks in advance
I don't think using Date() is the solution. You can do
var crDate = '23.10.2017';
var newDateF = crDate.split(".");
var temp = newDateF[0];
newDateF[0] = newDateF[1];
newDateF[1] = temp;
newDateF.join("/");
This splits the string into an array, swaps the first and second elements, and then joins back on a slash.
A regex replacement will do the trick without any Date functions.
var date = '23.10.2017';
var regex = /([0-9]{2})\.([0-9]{2})\.([0-9]{4})/;
console.log(date.replace(regex,'$2/$1/$3'));
Just use moment.js if you can :
// convert a date from/to specific format
moment("23.10.2017", "DD.MM.YYYY").format('MM/DD/YYYY')
// get the current date in a specific format
moment().format('MM/DD/YYYY')
Moment is a very usefull and powerfull date/time library for Javascript.
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));
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Extending JavaScript's Date.parse to allow for DD/MM/YYYY (non-US formatted dates)?
Convert dd-mm-yyyy string to date
Entered a date in textbox, for example: 05/09/1985, and I wanted to convert it to 05-Sep-1985 (dd-MMM-yyyy) format. How would I achieve this? Note that the source format may be dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format.
Code Snippet:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val());
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
This code returns 09-May-1985 but I want 05-Sep-1985. Thanks.
You might want to use helper library like http://momentjs.com/ which wraps the native javascript date object for easier manipulations
Then you can do things like:
var day = moment("12-25-1995", "MM-DD-YYYY");
or
var day = moment("25/12/1995", "DD/MM/YYYY");
then operate on the date
day.add('days', 7)
and to get the native javascript date
day.toDate();
Update
Below you've said:
Sorry, i can't predict date format before, it should be like dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format finally i wanted to convert all this format to dd-MMM-yyyy format.
That completely changes the question. It'll be much more complex if you can't control the format. There is nothing built into JavaScript that will let you specify a date format. Officially, the only date format supported by JavaScript is a simplified version of ISO-8601: yyyy-mm-dd, although in practice almost all browsers also support yyyy/mm/dd as well. But other than that, you have to write the code yourself or (and this makes much more sense) use a good library. I'd probably use a library like moment.js or DateJS (although DateJS hasn't been maintained in years).
Original answer:
If the format is always dd/mm/yyyy, then this is trivial:
var parts = str.split("/");
var dt = new Date(parseInt(parts[2], 10),
parseInt(parts[1], 10) - 1,
parseInt(parts[0], 10));
split splits a string on the given delimiter. Then we use parseInt to convert the strings into numbers, and we use the new Date constructor to build a Date from those parts: The third part will be the year, the second part the month, and the first part the day. Date uses zero-based month numbers, and so we have to subtract one from the month number.
Date.parse recognizes only specific formats, and you don't have the option of telling it what your input format is. In this case it thinks that the input is in the format mm/dd/yyyy, so the result is wrong.
To fix this, you need either to parse the input yourself (e.g. with String.split) and then manually construct a Date object, or use a more full-featured library such as datejs.
Example for manual parsing:
var input = $('#' + controlName).val();
var parts = str.split("/");
var d1 = new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));
Example using date.js:
var input = $('#' + controlName).val();
var d1 = Date.parseExact(input, "d/M/yyyy");
Try this:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val().toString().replace(/([0-9]+)\/([0-9]+)/,'$2/$1'));
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
The RegExp replace .replace(/([0-9]+)\/([0-9]+)/,'$2/$1') change day/month position.
See this http://blog.stevenlevithan.com/archives/date-time-format
you can do anything with date.
file : http://stevenlevithan.com/assets/misc/date.format.js
add this to your html code using script tag and to use you can use it as :
var now = new Date();
now.format("m/dd/yy");
// Returns, e.g., 6/09/07
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
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.