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
Related
I have spent several hours trying to figure out how JavaScript works with dates. I have come across this question, but it does not seem to asnwer my specific question.
My input is a string like this:
"2018-02-19T07:00:00Z"
My goal is to transform this into a datetime which would differ from the original date by 4 hours - WITHOUT ANY TIMEZONE (!):
"2018-02-19T11:00:00Z"
Is it possible in JavaScript ?
Check out all the functions relating to "UTC" and "ISO" on the Date docs.
var input = "2018-02-19T07:00:00Z";
var t = new Date(input);
t.setUTCHours(t.getUTCHours()+4)
var iso = t.toISOString().replace(/\.\d+/,'');
console.log(iso);
(I added a little regex to get rid of the milliseconds so it matches your expected output, you can remove that if the miliseconds don't matter, it's valid ISO either way.)
It's 4 lines of code, you do not need a library.
In addition to #Occam'sRazor answer, you could also do it without using the Date object, by using some String manipulations :
var str = "2018-02-19T07:00:00Z";
var timeZoneHours = +str.split('-').pop().split(':')[0].split('T').pop() + 4;
console.log(timeZoneHours);
str = str.substring(0,str.indexOf(':') -2) + (timeZoneHours < 10 ? '0' + timeZoneHours.toString() : timeZoneHours.toString()) + str.substring(str.indexOf(':'), str.length);
console.log(str);
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
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.
Using newDate() function in Java script, I am able to get today's date. I am getting the date in the format 3/3/2009 (d/m/yyyy). But i actually need the date in the format 2009-03-03 (yyyy-mm-dd). Can anyone pls let me know how to format the date as i require?
You usually have to write your own function to handle the formatting of the date as javascript doesn't include nice methods to format dates in user defined ways. You can find some nice pieces of code on the net as this has been done to death, try this:
http://blog.stevenlevithan.com/archives/date-time-format
Edit: The above code seems to be really nice, and installs a cool 'format' method via the date object's prototype. I would use that one.
If you want to roll-your-own, which is not too difficult, you can use the built-in javascript Date Object methods.
For example, to get the current date in the format you want, you could do:
var myDate = new Date();
var dateStr = myDate.getFullYear +
'-' + (myDate.getMonth()+1) + '-' + myDate.getDate();
You may need to zero-pad the getDate() method if you require the two-digit format on the day.
I create a few useful js functions for date conversions and use those in my applications.
There's a very nice library to manage date in JS.
Try this.
You'll pretty much have to format it yourself, yeah.
var curDate = new Date();
var year = curDate.getFullYear();
var month = curDate.getMonth() + 1;
var date = curDate.getDate();
if (month < 10) month = "0" + month;
if (date < 10) date = "0" + date;
var dateString = year + "-" + month + "-" + date;
It's a bit long, but it'll work (:
add jquery ui plugin in your page.
function DateFormate(dateFormate, dateTime) {
return $.datepicker.formatDate(dateFormate, dateTime);
};
Just another option, which I wrote:
DP_DateExtensions Library
Not sure if it'll help, but I've found it useful in several projects.
Supports date/time formatting, date math (add/subtract date parts), date compare, date parsing, etc. It's liberally open sourced.
No reason to consider it if you're already using a framework (they're all capable), but if you just need to quickly add date manipulation to a project give it a chance.