This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 9 years ago.
I have a function which accepts a UTC date. I want to return back the local date.
I have the following code so far:
var dateFormat = function (date) {
var dt = new Date(date + " UTC");
return dt.toString();
}
For the return date, I like it formatted as such:
October 9th, 2013, 7:34:00 PM
Is there a formatting that will handle this.
I usually use moment.js for this kind of tasks. It's pretty powerful and still small sized library. Give it a try.
You have a lot of ways to format the Date object in JavaScript. I suggest you to check out 10 ways to format time and date using JavaScript and Working with Dates. These are the main functions you need to use for formatting JavaScript Dates:
getDate(): Returns the date
getMonth(): Returns the month (Starting from 0)
getFullYear(): Returns the year
A simple script would be:
<script type="text/javascript">
var d = new Date();
var curDate = d.getDate();
var curMonth = d.getMonth() + 1; // Months are zero based
var curYear = d.getFullYear();
document.write(curDate + "-" + curMonth + "-" + curYear);
</script>
In your case, you can have an array of months:
var months = ["January", "February", ... "December"];
The next part would be associating the correct variables with the place they need to be present.
Plugins
But instead of doing all these, you can also consider using a fancy date formatter plugin, that uses jQuery or some library. A few ones would be:
Moment.js is a javascript date library for parsing, validating, manipulating, and formatting dates.
XDate is a thin wrapper around JavaScript's native Date object that provides enhanced functionality for parsing, formatting, and manipulating dates. It implements the same methods as the native Date, so it should seem very familiar.
DateJS is an open source JavaScript Date library for parsing, formatting and processing.
Related
This question already has answers here:
Format a date string in javascript
(7 answers)
Closed 2 years ago.
How do I format the date I receive from openweather api?
I currently get 2020-10-16 00:00:00 and I want 10-16-2020.
The reason I don't use moment is because I want future dates which come automatically with the 5 day forecast in the api.
You can use JavaScript's Date object.
You might save yourself time by searching a bit more before posting a question, the answer is probably already out there.
Where can I find documentation on formatting a date in JavaScript?
How to format a JavaScript date
Format JavaScript date as yyyy-mm-dd
You could try to:
Make a new date based on the date that comes from OpenWeather api
Convert it to a LocaleDateString using the 'en-US' locale. This will make the month appear before the date.
Then just split the Date String on the '/' and join in on a '-'. This will substitute the '/' with a '-'
const date = new Date("2020-10-16 00:00:00").toLocaleDateString('en-US');
const formatedDate = date.split('/').join('-');
console.log(formatedDate);
You can always use the built in Javascript Date object.
In your case you'd want to. do something like this -
const myDate = new Date('2020-10-16 00:00:00');
const date = myDate.getDate();
const month = myDate.getMonth() + 1;
const year = myDate.getFullYear();
console.log('MM-DD-YYYY', `${month}-${date}-${year}`);
If you want something more convinient and don't want to use moment you can also try some other popular date libraries. You can find some here - https://github.com/you-dont-need/You-Dont-Need-Momentjs
I am trying to read all dates in a table and see if those dates are old dates than current date time and if those are old dates then highlight those dates with some color.
Here is my Javascript code
$(".ticket-gird-td-duedate").each(function(i, e) {
debugger;
var dueDateAsString = $(e).text();
console.log(dueDateAsString);
var dueDate = new Date(dueDateAsString);
var currentdate = new Date();
if (dueDate < currentdate) {
//mark date in red color
console.log("I need to change color for this date as this is past date" + dueDate);
}
});
Problem here is dueDateAsString comes as "07/10/2017 18:30 PM"
And when I am doing
new Date("07/10/2017 18:30 PM")
it fails with invalid date error
Invalid Date
How can I convert my string date to Javascript date and proceed to compare it with current date?
That isn't a valid date, as you either have 24hr format or AM|PM 12hr format.
This works:
new Date('07/10/2017 18:30'); // No 'PM' after the 24hr time
Also note that JS dates are mutable, so todayDate and check will hold the same date value, but check will be a number.
You call this one first
todayDate.setDate(todayDate.getDate() - 5);
It will update todayDate to 5 days ago. Then you just assign it to check or you todayDate further.
var check = todayDate;
Hope this helps.
You can do this by using moment.js library (yet another terrific way to achieve date parsing).
Moment.Js library is freely available. You can use either a minified or full version of this library as you require. In this
library all the operations are performed on a moment object so the
date or time is stored in this library as a moment object only. So
this moment object is the core of this entire library. You can find
this library at Moment.js site's home page.
Add momentjs library reference into your project - https://momentjs.com/downloads/moment.js
updated code with moment.js would be:
var todayDate = new moment().format("MM/DD/YYYY h:mm:ss a");
var yesterday = todayDate.toLocaleString();
var check = moment(todayDate, "MM/DD/YYYY h:mm:ss a").add('days', -5);
alert("Your Old Date is- " + todayDate);
alert(check);
alert("Your Old Date is- " + yesterday);
JavaScript fiddle
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
This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 9 years ago.
I have this date here 2013/06/10, which comes from the database and is set in a variable called date.
I added one day to this date by doing this..
var endDate = new Date(date);
endDate.setDate(endDate.getDate() + 1);
and now I am trying to change the format to yyyy/MM/dd
var finalEndDate = endDate.toString('yyyy/MM/dd');
alert(finalEndDate);
but this returns
Tues Jun 11 2013 Eastern Standard Time, etc.
How do I fix this?
As far as I know, toString does not take any arguments. It's easy to construct your format though.
var finalEndDate = endDate.getFullYear() + '/' + (endDate.getMonth() + 1) + '/' + endDate.getDate();
There are several getter methods for each component of the date object to help you construct nearly any format.
I strongly encourage you to take a look at Moment.js
var str = moment(date, 'YYYY/MM/DD').add('days', 1).format('yyyy/MM/dd');
Note: moment doesn't know yyyy, what's that supposed to be? See http://momentjs.com/docs/#/displaying/format/ for supported format strings.
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.