I have a date format that is like this
"5-2015"
How can I convert it so that it appears as "May 2015" on screen?
You could try MomentJS http://momentjs.com/ which is a Date/Time library for Javascript. I believe the syntax would be moment(yourDate, 'M-YYYY').format('MMM YYYY');
If you want to roll your own:
function format(date) {
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var month = date.substring(0, date.indexOf('-'));
var year = date.substring(date.indexOf('-') + 1);
return months[parseInt(month) - 1] + ' ' + year;
}
var formatted = format('5-2015');
Assuming all of your dates are in the format of "5-2015" (e.g. 6-2015 or 12-2015), what you can do is use the split function on javascript split the string value into months and years.
For example:
var date = "5-2015";
date.split("-"); //splits the date whenever it sees the dash
var month;
if(date[0] == "5"){ //accesses the first split value (the month value) and check if it's a month.
month = "May";
} //do this with the rest of the months.
var finalString = month + " " + date[1]; //constructs the final string, i.e. May 2015
alert(finalString);
You can go like this:
function parseDate(dateString) {
var d = dateString.split("-"); // ["5", "2015"]
// Month is 0-based, so subtract 1
var D = new Date(d[1], d[0]-1).toString().split(" "); // ["Fri", "May", "01", "2015", "00:00:00", "GMT+0200", "(Central", "Europe", "Daylight", "Time)"]
return D[1] + " " + D[3];
}
(function() {
alert(parseDate("5-2015"));
}());
Related
My current time zone is getting added when converting date using "new Date()".
var date = "2019-06-03T23:32:59.2354387Z";
var date1 = new Date(date);
console.log(date1);
Expected result: 03-Jun-19 23:32:00
Actual result: 04-Jun-19 02:32:00
please find the fiddle here
https://jsfiddle.net/as6htw9p/
More specific to your scenario with keeping the format, this should work. It's just a shame that the integers provided are formatted like '1' instead of '01' so I have had to add a ‘0’ to the start of the variables.
This should output the exact result you want.
var date = new Date();
var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
'Sep', 'Oct', 'Nov', 'Dec']
var day = '0' + (date.getDay() + 2); // 003
day = day.slice(-2) + '-'; // 03-
var month = date.getMonth(); // 5
month = monthNames[month]; // Jun
month = month + '-'; // Jun-
var year = date.getFullYear() + ''; // 2019
year = year.slice(-2) + ' '; // 19
var hour = '0' + date.getHours(); // 018
hour = hour.slice(-2) + ':'; // 18:
var minutes = '0' + date.getMinutes(); // 025
minutes = minutes.slice(-2) + ':'; // 25:
var seconds = '0' + date.getSeconds(); // 06
seconds = seconds.slice(-2); // 06
var now = day + month + year + hour + minutes + seconds;
Date output in JavaScript is by default in local time. You should use UTC get/set if you need GMT format.
Try this:
utc_date = date1.toUTCString();
console.log(utc_date);
I have some unique data that I need to convert
Need to convert "01/23/2017" to 23-Jan-17 (Fri)
Also need to convert 0238 // I'm thinking that this is 2 hours and 38 minutes?
Finally convert 15:00 // I assume military? to 3:00pm ?
Sample data
"ArrivalDate": "01/23/2017",
"DepartureDate": "01/23/2017",
"DepartureAirport": "ORD",
"DepartureTime": "15:00",
"ArrivalAirport": "MCO",
"ArrivalTime": "18:38",
"TravelTime": "0238",
You can create two AngularJS filters using these methods getTravelDateFormatted and getTravelDateFormatted:
var getTravelDateFormatted = function (str) {
var daysNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'],
d = new Date(str),
day = d.getDate(),
month = monthNames[d.getMonth()],
year = d.getFullYear().toString().substr(2, 2),
dayName = daysNames[d.getDay()];
return day + '-' + month + '-' + year + ' (' + dayName + ')';
},
getTravelTimeFormatted = function (str) {
var hours = Math.trunc(str / 60),
minutes = str % 60;
return hours + ':' + minutes;
};
console.log(getTravelDateFormatted('01/23/2017'));
console.log(getTravelTimeFormatted('0238'));
Since you have provide very less information, i could only give you some suggestion below:
It's better you can make your input is in datetime format, like 1482826055407, then you can get any displayed date format you like via angular date filter or you can create a custom date filter.
Here is an example of custom date filter which used moment to support globalization, If you don't need that feature, you can replace it with angular $filter('date') service.
angular.module('aaa.ccc')
.filter('momentDate', [
function () {
'use strict';
return function (timestamp) {
if(!isNaN(parseInt(timestamp))){
return moment(parseInt(timestamp)).format('L');
}
};
}
]);
You can use angularjs date filter
First of all you need to convert string to date $scope.someDate = new Date('01/23/2017')
Then use angular filter in the view {{someDate | date:'dd-MMM-yy (EEE)'}}
Or you can use date filter via $filter in controller.
I have the following code on a page:
<span class="release-date"><i class="fa fa-calendar"></i> 2014-11-16</span>
This 2014-11-16 is the date and is generated automatically by my CMS. I need to change this date. Basically I need to change the month to read differently because this site has an international audience. In the case above I want it to read like this: 2014-Nov-16.
I know this can be done using a RegEx, however, I have no idea how to write this RegEx as I am not good at them. Of course in my example above 11 = Nov, 12 would equal Dec and so on for each month.
Here's a snippets with jQuery and Moment.js that does what you want, I made format into a variable so you can play with is.
$('.release-date').each( function() {
var format = "Do MMM YYYY";
var $this = $( this );
var old_date = $.trim($this.text());
var new_date = moment(old_date , 'YYYY-MM-DD').format( format );
$this.text($this.text().replace(old_date, new_date));
});
<script src="http://momentjs.com/downloads/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="release-date"><i class="fa fa-calendar"></i> 2014-11-16</span>
You can use the Javascript Date to save you some ugly regex
new Date("2014-11-16")
>> Sat Nov 15 2014 16:00:00 GMT-0800 (PST)
new Date("2014-11-16 PST")
>> Sun Nov 16 2014 00:00:00 GMT-0800 (PST)
Unless you add another library like momemt.js or something, you may need to add a little helper to get the month as a string. Something like:
function monthToString(month) {
var months = [ 'Jan', 'Feb', ... , 'Dec' ];
return months[month % months.length]
}
Then you can build the new date string like this
function convertDateString(dateFromCms) {
var date = new Date(dateFromCms);
return date.getFullYear() + "-" + monthToString(date.getMonth()) + "-" + date.getDate();
}
Or something along those lines. Check out the MDN for more about how Date works.
If you want to select the textNode of the span elements, you can iterate through their childNodes and filter the textNode:
[].forEach.call(document.querySelectorAll('.release-date'), function(el) {
var n = el.childNodes, inputDate;
for ( var i = n.length; i--; ) {
if ( n[i].nodeType === 3 && n[i].nodeValue.trim().length ) {
inputDate = n[i].nodeValue.trim();
n[i].nodeValue = // modify the input date
}
}
});
You can do it this way:
Fiddle
var elem = document.getElementsByClassName('release-date')[0];
var text = elem.innerHTML;
var regex = /-(\d{1,2})-/m
var month = regex.exec(text);
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'August', 'Sept', 'Oct', 'Nov', 'Dec']
if (month[1]) {
elem.innerHTML = text.replace(regex, "-" + months[parseInt(month[1], 10) - 1] + "-")
}
This works too..
var months = {
1: 'jan',
2: 'feb',
3: 'march',
4: 'apr',
5: 'may',
6: 'june',
7: 'july',
8: 'aug',
9: 'sep',
10: 'oct',
11: 'nov',
12: 'dec'
};
var currentDate = "2014-11-16"; // your date string would go here. Note, I left the retrieval of it out. This is trivial w/ jQuery... $('.release-date').text();
var redrawnCurrentDate = currentDate.replace(/(\d{2})-(\d{2})$/,function(_,$1,$2){
return months[$1] + "-" + $2;
});
$('.release-date').text(redrawnCurrentDate);
This question already has answers here:
Compare two dates with JavaScript
(44 answers)
Closed 8 years ago.
I am trying to do date comparison in javascript.Through a web service call I am getting a date in the form of ""2014-07-02T09:49:49.299Z" and from database I am getting the dat like "2014-07-11 16:01:34".I need to compare these two dates after doing some kind of formatting.i am not sure how to format these two kind of dates to a common format.
Thanks in advance.....
You have date string like : -
var date = "2014-07-02T09:49:49.299Z"
You can try this:-
var getDateString = function(date, format) {
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
getPaddedComp = function(comp) {
return ((parseInt(comp) < 10) ? ('0' + comp) : comp)
},
formattedDate = format,
o = {
"y+": date.getFullYear(), // year
"M+": months[date.getMonth()], //month
"d+": getPaddedComp(date.getDate()), //day
"h+": getPaddedComp((date.getHours() > 12) ? date.getHours() % 12 : date.getHours()), //hour
"m+": getPaddedComp(date.getMinutes()), //minute
"s+": getPaddedComp(date.getSeconds()), //second
"S+": getPaddedComp(date.getMilliseconds()), //millisecond,
"t+": (date.getHours() >= 12) ? 'PM' : 'AM'
};
for (var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
formattedDate = formattedDate.replace(RegExp.$1, o[k]);
}
}
return formattedDate;
};
Now to format the date, write:-
getDateString(new Date(date), "h:m:s:t")
And to compare two dates try this
var date = "2014-07-02T09:49:49.299Z";
var date1 = "2013-07-02T09:49:49.299Z";
var compareDate = function(date,date1){
if(new Date(date).getTime()>new Date(date1).getTime()){
console.log("greater date");
} else{
console.log("lesser date");
}
}
This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 8 years ago.
I need your help,
how can I rework and restring a date string from yyyy-mm-ddd to dd/mm/yyyy?
Example: 2014-06-27, firstly replace the dash with a slash, then shift the order of the digits around to form 27/06/2014
I am not sure as to how to go about doing this?
Thanks
I've made a custom date string format function, you can use that.
var getDateString = function(date, format) {
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
getPaddedComp = function(comp) {
return ((parseInt(comp) < 10) ? ('0' + comp) : comp)
},
formattedDate = format,
o = {
"y+": date.getFullYear(), // year
"M+": months[date.getMonth()], //month
"d+": getPaddedComp(date.getDate()), //day
"h+": getPaddedComp((date.getHours() > 12) ? date.getHours() % 12 : date.getHours()), //hour
"H+": getPaddedComp(date.getHours()), //hour
"m+": getPaddedComp(date.getMinutes()), //minute
"s+": getPaddedComp(date.getSeconds()), //second
"S+": getPaddedComp(date.getMilliseconds()), //millisecond,
"t+": (date.getHours() >= 12) ? 'PM' : 'AM'
};
for (var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
formattedDate = formattedDate.replace(RegExp.$1, o[k]);
}
}
return formattedDate;
};
And now suppose you've :-
var date = "2014-06-27";
So to format this date you write:-
var formattedDate = getDateString(new Date(date), "d/M/y")
if you're using a string, then the string.split would be an easy way to do this.
C# code:
public void testDateTime()
{
string dashedDate = "2014-01-18"; // yyyy-mm-dd
var stringArray = dashedDate.Split('-');
string newDate = stringArray[2] + "/" + stringArray[1] + "/" + stringArray[0];
//convert to dd/mm/yyyy
Assert.AreEqual(newDate, "18/01/2014");
}