Converting UTC date to mm/dd/yyyy - javascript

I am having a date in isoUtc format and I want to convert it into mm/dd/yyyy format. I tried to use the hint given in this blog entry but the problem I am facing is that if I convert 2007-04-06T00:00Z it gives different dates when user time zone is different. I want that it should give 04/06/2007 always independent of the user timezone.
Any help is appreciated

var d = '2007-04-06T00:00Z';
var d2 = d.substring(5,7)+'/'+d.substring(8,10)+'/'+d.substring(0,4);
// outputs 04/06/2007

You could thy this, if you have always constant format:
var dateString = '2007-04-06T00:00Z',
dateRegExp = /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/,
match = dateString.match(dateRegExp),
date;
if (match) {
date = new Date(match[1], match[2] - 1, match[3], match[4], match[5]);
console.log(date);
}
DEMO

Related

Converting date formats without timezone conversion?

I'm trying to do this without adding moment js to my project but it seems more difficult than I'd like.
if I get a date that's formatted as : "2021-07-19T12:15:00-07:00"
Is there an efficient way to have it formatted as:
"12:15 pm"
regardless of where me and my browser are located?
I've gotten as far as some other answers with no luck, for example:
var date = new Date('2021-07-19T12:15:00-07:00')
var userTimezoneOffset = date.getTimezoneOffset() * 60000;
new Date(date.getTime() - userTimezoneOffset);
Thanks!
You could use Date.toLocaleTimeString() to format the time, this will give you the time in the local timezone, if we remove the UTC offset.
There are other options available here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat
let timestampWithUTCOffset = "2021-07-19T12:15:00-07:00";
let timestampWithoutUTCOffset = timestampWithUTCOffset.substr(0,19);
console.log( { timestampWithUTCOffset , timestampWithoutUTCOffset });
let dt = new Date(timestampWithoutUTCOffset);
console.log('Time of day:', dt.toLocaleTimeString('en-US', { timeStyle: 'short' }))

Parsing a date in javascript

First of all thanks in advance for helping, the community is great.
I have a problem parsing my date and time. Here is my code:
var date = mail.bodyText.match(/\=\= date \=\=\s*(.*[^\s*])/);
if (date) {
var string1 = date[1].match(/^\d{4}\-\d{2}-\d{2}/);
var string2 = date[2].match(\s(\d{2}\:\d{2}\:\d{2}));
var string3 = date[3].match(\s(\+\d{4}));
var parts1 = string1.split("-");
var parts2 = string2.split(":");
if (parts1 && parts2)
{
var dt = new Date(parseInt(parts1[0], 10), parseInt(parts1[1], 10) - 1, parseInt(parts1[2], 10), parseInt(parts2[3], 10), parseInt(parts2[4], 10), parseInt(parts2[5], 10));
}
date_final = dt;
}
date_final is defined elsewhere, and is in Date Time Picker format, and here is the input I am trying to parse:
blabla
== date ==
2016-02-13 16:22:10 +0200
blabla
Every time I execute the code, I get a parsing problem. The variable date_final cannot handle the parsed date. What do you think is missing from this code?
Update:
Here is what I'v etried out. Impossible for me to locate what's wrong:
var date = mail.bodyText.match(/\=\= date \=\=\s*(.*[^\s*])/);
if (date) {
var initial = date[1];
var formated = initial.substring(0, 19);
var final = formated.replace(/-/g, '/');
var last = new Date(final);
Field = last;
logging += "{date=" + Field + "}";
}
The code is actually parsing an email and sending the result over SSL. What surprises me the most is that the logs keep posting the following output of the date i naddition to the "parsing issue": date=Sat Feb 27 2016 16:22:10 GMT+0200 (CEST).
Do you think the problem comes from the code or could be related to how the appliance this code implemented on can handle it?
Thanks
Jane
Sorry for answering in comment.
Here's one solution to your question:
var dateStr = '2016-02-13 16:22:10 +0200';
// get yyyy-MM-dd HH:mm:ss
var formatedStr = dateStr.substring(0, 19);
// get yyyy/MM/dd HH:mm:ss in case of working on most of the browsers
var finalStr = formatedStr.replace(/-/g, '/');
// Date object can easily parse the datetime string we formated above
var date = new Date(finalStr);
Date object can parse complex strings.
Mail providers usually follow an RFC on how timestamps should be written, thus allowing other programming languages to heavily support it.
Just pass your string into date object and it will convert it for you.
let mailStr = `blabla
== date ==
2016-02-13 16:22:10 +0200
blabla`;
let regex = mailStr.match(/\=\= date \=\=\s*(.*[^\s*])/);
let dt = new Date(regex[1]);
console.log(dt);
The output is described in ISO-8601

JavaScript new Date('22/22/2222') convert to a valid date in IE 11

var checkDate = new Date("22/22/2222");
When I check in IE 11 it convert to Wed Oct 22 00:00:00 EDT 2223 so my next line fails
if (checkDate != 'Invalid Date')
How to fix it?
As you've passed in an invalid date format (as far as the ECMA spec is concerned), the browser is free to choose to interpret it how it wishes. It seems IE thinks it can deal with it:
The function first attempts to parse the format of the String according to the rules (including extended years) called out in Date Time String Format (20.3.1.16). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.
If you're going to pass in strange formats, you're either going to need to validate them yourself or use a library that can do so better than the browsers can.
Months and days can "wrap" in JavaScript. One way to test if the date is legal is to see if the output date corresponds to the original input string. If it doesn't, then it wrapped.
function check(inputString) {
var checkDate = new Date(inputString);
// Get month, day, and year parts, assuming
// you don't have them already
var arr = inputString.split('/');
var isMonthWrapped = +arr[0] !== checkDate.getMonth() + 1;
var isDayWrapped = +arr[1] !== checkDate.getDate();
var isYearWrapped = +arr[2] !== checkDate.getFullYear();
console.log("Parts", +arr[0], +arr[1], +arr[2]);
console.log("Results", checkDate.getMonth() + 1, checkDate.getDate(), checkDate.getFullYear());
console.log("Wrapped?", isMonthWrapped, isDayWrapped, isYearWrapped);
var isLegal = checkDate !== 'Invalid Date' && !isMonthWrapped && !isDayWrapped && !isYearWrapped;
document.body.innerHTML += inputString + ': ' + (isLegal ? 'Legal' : 'Illegal') + '<br>';
};
check("22/22/2222");
check("12/12/2222");
I think that moment.js http://momentjs.com/ is a complete and good package about dates.
You could add string date and format.
moment("12/25/1995", "MM/DD/YYYY");
And you could check if date is valid.
moment("not a real date").isValid();
See documentation
http://momentjs.com/docs/#/parsing/string-format/
You should break up your string and parse Each date to integers individually. It will be much safer.
Do something like this
var dateString = "22/22/2222";
dateString.indexOf("/");
var day = parseInt(dateString.slice(0,dateString.indexOf("/")));
dateString = dateString.slice(1+dateString.indexOf("/"), dateString.length);
var month = parseInt(dateString.slice(0,dateString.indexOf("/")))
dateString = dateString.slice(1+dateString.indexOf("/"), dateString.length);
var year = parseInt(dateString);
console.log(day, month, year);
var date = new Date(0);
if(month>12) console.log("hey this is totally not a valid month maaaan!")
date.setDate(day);
date.setMonth(month);
date.setYear(year);
console.log(date);

Changing date format javascript

I'm pulling some data from two different APIs and I want to the objects later on.
However, I'm getting two different date formats: this format "1427457730" and this format "2015-04-10T09:12:22Z". How can I change the format of one of these so I have the same format to work with?
$.each(object, function(index) {
date = object[index].updated_at;
}
Here's one option:
var timestamp = 1427457730;
var date = new Date(timestamp * 1000); // wants milliseconds, not seconds
var dateString = date.toISOString().replace(/\.\d+Z/, 'Z'); // remove the ms
dateString will now be 2015-03-27T12:02:10Z.
Try moment.js
var timestamp = 1427457730;
var date = '2015-04-10T09:12:22Z';
var m1 = moment(timestamp);
var m2 = moment(date);
console.log(m1);
console.log(m2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
You can use .format() method in moment to parse the date to whatever format you want, just like:
m2.format('YYYY MMM DD ddd HH:mm:ss') // 2015 Apr 10 Fri 17:12:22
Check out the docs for more format tokens.
What you probably want in javascript, are date objects.
The first string is seconds since epoch, javascript needs milliseconds, so multiply it by 1000;
The second string is a valid ISO date, so if the string contains a hyphen just pass it into new Date.
var date = returned_date.indexOf('-') !== -1 ? returned_date : returned_date * 1000;
var date_object = new Date(date);
Making both types into date objects, you could even turn that into a handy function
function format_date(date) {
return new Date(date.indexOf('-') !== -1 ? date : date * 1000);
}
FIDDLE
Take a look at http://momentjs.com/. It is THE date/time formatting library for JavaScript - very simple to use, extremely flexible.

Reading the date from textbox as a string and converting it into as Date

I am reading the date from textbox by using javascript and trying to convert it as Date object.But my problem is date is converting as month and month is converting as date when converting the string to date.
Example:
03/12/2014 the value in the textbox
Actual Output:
03 as March,
12 as date (Its wrong)
Expected Output:
03 as date
12 as December (I am expecting)
While converting this string to date by using following snippet
var startTime = document.getElementById("meeting:startTime");
date.js
var stringToDate_startTime=new Date(Date.parse(startTime.value,"dd/mm/yy"));
moment.js
var date1=moment(startTime.value).format('DD-MM-YYYY');
In the above even i have used date.js and moment.js files also.But those also did not solve my problem.Please can anyone help me out to get rid out of this.
Try ...
var from = startTime.value.split("/");
var newDate = newDate(from[2], from[1] - 1, from[0]);
... assuming time included ...
var date_only = startTime.value.split("");
var from = date_only[0].split("/");
var newDate = newDate(from[2], from[1] - 1, from[0]);
I am not aware of an implementation of the Date.parse() method that accepts two arguments. You can view the Mozilla Date.parse() method description here Date.parse() - JavaScript | MDN.
It might be worth looking at the question/answer of this question for some more information: Why does Date.parse give incorrect results?
The next best option would be to split the date using String.split() and to rearrange the date parts
var dateStr = '03/12/2014 23:05';
var newDateStr = null;
var dateParts = dateStr.split('/');
if (dateParts.length == 3) {
var day = dateParts[0];
var month = dateParts[1];
var yearAndTime = dateParts[2];
// Rearrange the month and day and rejoin the date "12/03/2014 23:05"
newDateStr = [ month, day, yearAndTime].join('/');
} else {
throw new Error('Date not in the expected format.');
}
var date = new Date(newDateStr); // JS Engine will parse the string automagically
alert(date);
This isn't the most elegant solution, but hopefully that helps.

Categories