I am getting string data from a Google Calendar feed. The date is already set, by parameter, with the desired timezone.
2014-05-24T07:00:00.000-04:00
I know there are wonderful libraries like moment.js and date.js this will help format my date, but they also work with a Date object, which throws my date into a client's culture. At that point I am then juggling offsets. Would rather avoid that.
Other than a lot of conditional string manipulation, is there a simple way to do this, or I am oversimplifying (again)?
Example:
2014-05-24T07:00:00.000-04:00 to May, 24, 2014 - 7:00 AM
The following short code will parse your date, using the values present, without offsetting by the timezone:
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var res = /(\d+)\-(\d+)\-(\d+)T(\d+)\:(\d+)/
.exec('2014-05-24T07:00:00.000-04:00');
var am = (res[4] < 12);
var date = months[res[2]-1] + ', ' + res[3] + ', ' + res[1];
var time = am ? (parseInt(res[4]) + ':' + res[5] + 'AM') :
(res[4] - 12 + ':' + res[5] + 'PM');
var formatted = date + ' - ' + time;
console.log(formatted);
You can convert this string into a Date object like below,
new Date("2014-05-24T07:00:00.000-04:00")
Then you can easily convert this date object into your desired format by using any of the jQuery libraries such as jquery.globalize.js ...
Here you go:
var d = new Date('2014-05-24T07:00:00.000-04:00');
var calendar = {
months: {
full: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
short: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
days: {
full: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
short: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
}
};
console.log(calendar.months.short[d.getMonth()]+', '+d.getDate()+', '+d.getFullYear());
A simple function to reformat the string is:
function reformatDateString(s) {
s = s.match(/\d+/g);
var months = ['January','February','March','April','May','June','July',
'August','September','October','November','December'];
var ampm = s[3]<12? 'AM':'PM';
return months[--s[1]] + ', ' + +s[2] + ', ' + s[0] + ' - ' +
(s[3]%12 || 12) + ':' + s[4] + ' ' + ampm;
}
console.log(reformatDateString('2014-05-24T07:00:00.000-04:00')); // May, 24, 2014 - 7:00 AM
console.log(reformatDateString('2014-05-24T17:00:00.000-04:00')); // May, 24, 2014 - 5:00 PM
console.log(reformatDateString('2014-05-04T00:20:00.000-04:00')); // May, 4, 2014 - 12:20 AM
Which also assumes that you don't want leading zeros on single digit numbers except for the minutes, as a time like 12:5 PM isn't as readable (to me) as 12:05 PM.
Also you may need to modify the months array, it's not clear in the OP whether you want full month names or abbreviations (Jan, Feb, etc.).
Related
I have a Date() object in Javascript. How can I convert it to show "Month Year" (example: Oct 2021).
I tried the following code and it works too. However, I have to convert a lot of dates to this format and it has performance issues.
const date = new Date();
const month = date.toLocaleString('default', { month: 'short' });
const year = date.toLocaleString('default', { year: 'numeric' });
Note: I don't want to use JQuery or other libraries.
If performance is such a concern, why not just reduce some complexity and use getMonth()/getYear() and manually map the abbreviated month names?
const date = new Date();
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
console.log(months[date.getMonth()] + " " + date.getFullYear())
It's provably faster than the other methods posited here, even with the requirement to declare months.
I have a function that I am trying to get to format the date and time or just the date at the moment.
function(){
var d = new Date();
var n = d.getTime();
return 'VZW Dfill - ' + n;}
What I have tried
function(){
var d = new Date();
return 'VZW Dfill - ' + d;}
This returns
VZW Dfill - Thu Jan 30 2020 103924 GMT-0500 (Eastern Standard Time)
I would like the format to be 2020JAN30
I have also tried the following but this does not work
function(){
var d = new Date('YYYYMDD');
return 'VZW Dfill - ' + d;}
The above breaks the function.
Any help is appreciated.
This is actually surprisingly complex using pure JavaScript. Here's one (of many) solutions:
var now = new Date();
var months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
var formattedDate = now.getFullYear() + months[now.getMonth()] + now.getDate();
alert(formattedDate);
Using your code from above, write the following function:
function(){
var d = new Date();
var months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
d = d.getFullYear() + months[d.getMonth()] + d.getDate();
return 'VZW Dfill - ' + d;}
There is a pretty extensive thread about formatting JavaScript dates here. Most of them involve (common) third party packages.
You can use also locale
console.log(today.toLocaleDateString("zh-TW")); // 2020/1/30
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"));
}());
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:
How to initialize a JavaScript Date to a particular time zone
(20 answers)
Closed 9 years ago.
This is simple current time zone clock so i want specific time zone like INDIA if any person open my site in US or any Out of India, that people can see INDIAN Time not US time.
So Please Can any one help to add specific time zone in this code.
function date_time(id)
{
date = new Date;
year = date.getFullYear();
month = date.getMonth();
//months = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'Jully', 'August', 'September', 'October', 'November', 'December');
d = date.getDate();
day = date.getDay();
days = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
//days = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
h = date.getHours();
if(h<10)
{
h = "0"+h;
}
m = date.getMinutes();
if(m<10)
{
m = "0"+m;
}
s = date.getSeconds();
if(s<10)
{
s = "0"+s;
}
result = ''+d+' '+months[month]+' '+year+' - '+days[day]+' - '+h+':'+m+':'+s;
document.getElementById(id).innerHTML = result;
setTimeout('date_time("'+id+'");','1000');
return true;
}
You may use this js timezone-js
for further reference you may refer this Question