Issue with converting string which is of DateTime to javascript Date - javascript

I have a string which contains DateTime as "20140121230000" . If i try to convert this into a Date.
var oDate = new Date(20140121230000);
i'm getting the year as 2068! Is there a way to convert this into a Date which is of year 2014, month 01 Date 21 Time 23:00:00 ?
Is it possible to directly convert this without doing any parsing in the string ?

Unless you use a library there is no way to convert the value without manually splitting the string.
var year = +oDate.slice( 0, 4);
var month = +oDate.slice( 4, 2) - 1; // Month is zero-based.
var day = +oDate.slice( 6, 2);
var hour = +oDate.slice( 8, 2);
var minute = +oDate.slice(10, 2);
var second = +oDate.slice(12, 2);
// This will interpret the date as local time date.
var date = new Date(year, month, day, hour, minute, second);
// This will interpret the date as UTC date.
var utcDate = Date.UTC(year, month, day, hour, minute, second);

The constructor you used takes millisecond since 1st Jan, 1970, try using :
var oDate = new Date(2014, 01, 21, 23, 00, 00, 00);
Note, month 01 will be Feb, not Jan.

Constructing a Date object with a string
new Date(string)
expects a date string that Date.parse can understand:
ISO 8601 (e.g. 2011-10-10T14:48:00), or
RFC2822 (e.g., Mon, 25 Dec 1995 13:30:00 GMT)
See MDN for more information on Date and Date.parse.
Yours is not a recognized format. You can either
reformat the string to fit one of the formats above
split the string manually and call Date with individual parameters, as in new Date(year, month, day, hour, minute, second, millisecond)
use a library like moment.js
Using moment.js would look something like this:
moment("20140121230000", "YYYYDDMMHHmmss")
See moment.js string + format for more information about the format syntax.

Given '20140121230000', you can split it into bits and give it to the Date constructor:
function parseSToDate(s) {
var b = s.match(/\d\d/g) || [];
return new Date( (b[0] + b[1]), --b[2], b[3], b[4], b[5], b[6]);
}
console.log(parseSToDate('20140121230000'));

Related

TypeScript: Remove Seconds from Date Object and Reconvert back to Date?

How Do I Remove Seconds from Date Object and Reconvert back to Date?
let testDate = new Date(2020, 05, 03, 1, 2);
This answer converts to ISO String, I dont want that, but return an actual Date.
Remove Seconds/ Milliseconds from Date convert to ISO String.
var date = new Date();
date.setSeconds(0, 0);
console.log(date);

How to specify timestamp format when converting to human readable string in JS

I need to display a formatted date from a timestamp provided by Google Analytics
Standard solution like
var date = new Date(timestamp * 1000);
var formatted = date.toString();
produces wrong value Jan 01 1970. That's because of timestamp format.
In PHP I can specify the timestamp format:
\DateTime::createFromFormat('Ymd', $timestamp);
How to do this in JS?
Since the dates you are receiving are formatted as YYYYMMDD, not as a Unix
timestamp, you can parse it by
extracting the year, month and date using String.prototype.slice.
var timestamp = '20170306',
year = parseInt(timestamp.slice(0, 4), 10),
month = parseInt(timestamp.slice(5, 6), 10),
day = parseInt(timestamp.slice(7, 8), 10);
// - 1 because the Date constructor expects a 0-based month
date = new Date(Date.UTC(year, month - 1, day)),
gmt = date.toGMTString(),
local = date.toString();
console.log('GMT:', gmt); // Mon, 06 Mar 2017 00:00:00 GMT
console.log('Local:', local);
This assumes that the dates you are using are in UTC (which they likely are). Date.UTC creates a timestamp (in milliseconds since Unix epoch) and then feeds it into new Date() which uses it to create a Date object representing that time. .toGMTString() outputs the date formatted for the GMT timezone. To output it formatted in local time, use .toString() instead.
try this type:
var userDate = new Date();
var day = userDate.getDate();
var month = userDate.getMonth() + 1;
var year = userDate.getFullYear();
alert("Date Formate is :"+year+"-"+month + "-" + day);
In javascript you can use an external library like moment.js
var date = moment.unix(timestamp);
date.format("YYYY MM DD");
See detail about .format here https://momentjs.com/docs/#/displaying/format/

UTC date convert to local timezone

I have a date in UTC format.
"2016-10-12 05:03:51"
I made a function to convert UTC date to my local time.
function FormatDate(date)
{
var arr = date.split(/[- :T]/), // from your example var date = "2012-11-14T06:57:36+0000";
date = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], 00);
var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
My Local timezone is GMT +0530.
My code produced this output:
Tue Oct 11 2016 10:33:00 GMT+0530 (IST)
I converted the date with an online tool to get the correct date and time.
Wednesday, October 12, 2016 10:30 AM
My code matches the online tool on time but not on date.
How can I correct my code's output, preferably using moment.js?
UTC is a standard, not a format. I assume you mean your strings use a zero offset, i.e. "2016-10-12 05:03:51" is "2016-10-12 05:03:51+0000"
You are on the right track when parsing the string, but you can use UTC methods to to stop the host from adjusting the values for the system offset when creating the date.
function parseDateUTC(s){
var arr = s.split(/\D/);
return new Date(Date.UTC(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]));
}
console.log(parseDateUTC('2016-10-12 05:03:51').toLocaleString());
If you want to use moment.js, you can do something like the following. It forces moment to use UTC when parsing the string, then local to write it to output:
var d = moment.utc('2016-10-12 05:03:51','YYYY-MM-DD HH:mm:ss');
console.log(d.local().format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.0/moment.js"></script>
Since you have tagged moment, I'm assuming you are using moment.
In such cases, you should keep your approach consistent and not mix moment and date object.
var dateStr = '2016-10-12 05:03:51';
var timeZone = "+0530";
var date = moment.utc(dateStr).utcOffset(dateStr + timeZone)
console.log(date.toString())

how to add time plus and recalculate the datetime

i have this datetime format:
Oct 31, 2012 08:59:52
i would like to re-calculate the datetime incremented (for example) of 2 hours or 50 minutes plus how can i do that?
i need to return the same datetime format showed above and not a timestamp!
var date = new Date("Oct 31, 2012 08:59:52");
var timeInMillis = date.getTime();
Now that you have time in milliseconds, you can just add the time you want in millis.
Eg: 2 hours? So, 2*60*60*1000 + timeInMillis
var newDate = new Date(2*60*60*1000 + timeInMillis);
If you want to convert your newDate into the original format, which is a long process, you can some guidance from here:
Where can I find documentation on formatting a date in JavaScript?
My pick of the answers would be:
Use MomentJS
You could first parse this to a date:
var d=new Date("October 31, 2012 08:59:25").getTime();
Then add the offset:
d+= (seconds)*1000 + (minutes)*60000 + (hours)*3600000;
var result = new Date(d);
I am just not sure wether it accepts 'Oct' instead of 'October'
time_start = new Date(year, month, day, hours, minutes, seconds, milliseconds);
time_finish = new Date() - time_start;
Set the Date using the format listed above. To calculate the interval between two points of time, just subtract the current date from the past date.

Regarding JavaScript new Date() and Date.parse()

var exampleDate='23-12-2010 23:12:00';
I want to convert above string into a date and have tried a couple things:
var date = new Date(exampleDate); //returns invalid Date
var date1 = Date.parse(exampleDate); //returns NAN
This code is running fine in IE and Opera, but date is returning me an invalid Date and date1 is returning NAN in Firefox. What should I do?
The string in your example is not in any of the standard formats recognized by browsers. The ECMAScript specification requires browsers to be able to parse only one standard format:
The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ
This format includes date-only forms:
YYYY
YYYY-MM
YYYY-MM-DD
It also includes time-only forms with an optional time zone offset appended:
THH:mm
THH:mm:ss
THH:mm:ss.sss
Also included are “date-times” which may be any combination of the above.
If the String does not conform to that format the function may fall back to any
implementation-specific heuristics or implementation-specific date formats. Unrecognizable Strings or dates
containing illegal element values in the format String shall cause Date.parse to return NaN.
So in your example, using 2010-12-23T23:12:00 is the only string guaranteed to work. In practice, most browsers also allow dates of the format DD Month YYYY or Month DD, YYYY, so strings like 23 Dec 2010 and Dec 23, 2010 could also work.
Above format is only supported in IE and Chrome.
so try with another formats. following are some formats and there supporting browsers.
<script type="text/javascript">
//var dateString = "03/20/2008"; // mm/dd/yyyy [IE, FF]
var dateString = "2008/03/20"; // yyyy/mm/dd [IE, FF]
// var dateString = "03-20-2008"; // mm-dd-yyyy [IE, Chrome]
// var dateString = "March 20, 2008"; // mmmm dd, yyyy [IE, FF]
// var dateString = "Mar 20, 2008"; // mmm dd, yyyy [IE, FF]
// Initalize the Date object by passing the date string variable
var myDate = new Date(dateString);
alert(myDate);
</script>
You could parse it manually with a regular expression then call the date constructor with the date elements, as such:
var parseDate = function(s) {
var re = /^(\d\d)-(\d\d)-(\d{4}) (\d\d):(\d\d):(\d\d)$/;
var m = re.exec(s);
return m ? new Date(m[3], m[2]-1, m[1], m[4], m[5], m[6]) : null;
};
var dateStr = '23-12-2010 23:12:00';
parseDate(dateStr).toString(); //=> Thu Dec 23 2010 23:12:00 GMT-0800
JavaScript should support conversion at least from the following dateStrings:
* yyyy/MM/dd
* MM/dd/yyyy
* MMMM dd, yyyy
* MMM dd, yyyy
Try with:
var exampleDate='12/23/2010 23:12:00';
var date = new Date(exampleDate);
Use datejs and this code:
var exampleDate='23-12-2010 23:12:00';
var myDate = Date.parseExact(exampleDate, 'dd-MM-yyyy hh:mm:ss');
myDate should be a correctly constructed Date object.
Just use in this format:
var exampleDate='2010-12-23 23:12:00';
#casablanca has a good answer but it's been 10+ years and this still has a lot of weight in Google so I thought I'd update with a new answer.
TL;DR
// Use an ISO or Unix time string to generate `Month DD, YYYY`
const newDate = new Date('23-12-2010')
const simpleDate = `${newDate.toLocaleString('en-us', { month: 'long' } )} ${newDate.getDate()}, ${newDate.getFullYear()}`
// yields: December, 23 2010 (if you want date suffix, read until the end)
Background: Dates come in a lot of formats, but you're mostly going to receive:
An ISO 8601 format date (YYYY-MM-DDTHH:mm:ss.sssZ) where Z is a UTC timezone offset. You might also get a subset of this (ie, YYYY-MM-DD)
Unix timestamp format date (1539734400), where the number is literally the total amount of milliseconds since the beginning of Unix time, Jan 1st 1970.
Basics: JS has a built-in Date prototype that accepts ISO 8601 and derivatives (of just time or just date). You can instantiate with new Date and return a date object OR you can use the Date.parse() method to return a Unix timestamp.
const dateObj = new Date('23-12-2010:23:12:00') // returns date object
const dateDateOnly = new Date('23-12-2010') // returns date object
const dateTimeOnly = new Date('23:12:00') // returns date object
const dateString = Date.parse('23-12-2010:23:12:00') // returns Unix timestamp string
You can also break the date into 7 parameters: the year, the month (starting from 0), the day, the hour, the minutes, seconds and milliseconds with the time zone offset - NOTE, I've used the multi-params approach only once in my career. Since I'm in Texas I get, UTC-5 (Central Time) when I run the following:
const dateByParam = new Date(2021, 2, 26, 13, 50, 13, 30) // Fri Mar 26 2021 13:50:13 GMT-0500 (Central Daylight Time)
New-ish Stuff toLocaleString: Typically, the return from the Date object is still pretty dense like our last example (Fri Mar 26 2021 13:50:13 GMT-0500 (Central Daylight Time) so additional methods have been added to help developers.
Typically with a date, I want something like March 21st, 2021 - the day and year have been easy to get for a long time:
// Assuming myDate is a JS Date object...
myDate.getDate() // date on the calendar, ie 22
myDate.getDay() // day of the week, where 0 means Sunday, 1 means monday, etc
myDate.getFullYear() // 4 digit year, ie, 2021
But I've always had to build a function to turn getDay into January, February, March, not anymore. toLocaleString() gives you some new superpowers. You can pass it two params, a string for region (ie, en-us) and an object with what you want back (ie, { month: 'long' }). This helps internationalize the response, if need be.
// Again, assuming myDate is a JS Date object...
myDate.toLocaleString('en-us', { month: 'long' } ) // March
Date Suffix I've still seen no built-in way to get the suffix for a date, like th, st, so I built this utility function that uses the modulus % operator to check the divisor of each day number and apply the right suffix (aimed at an American audience but might be the same elsewhere?).
/**
* setDateSuffix()
*
* Desc: Takes two digit date, adds 'st', 'nd', 'rd', etc
*
* #param { integer } num - a number date
*/
export const setDateSuffix = (num) => {
const j = num % 10,
k = num % 100
if (j === 1 && k !== 11) {
return num + "st";
}
if (j === 2 && k !== 12) {
return num + "nd";
}
if (j === 3 && k !== 13) {
return num + "rd";
}
return num + "th";
}
Altogether now.. Long winded way of getting here, but if I am given an ISO or Unix date and I want Month DDth, YYYY, this is what I run:
// setDateSuffix IS NOT PART OF BUILT-IN JS!
const newDate = new Date('23-12-2010')
const simpleDate = `${newDate.toLocaleString('en-us', { month: 'long' } )} ${setDateSuffix(newDate.getDate())}, ${newDate.getFullYear()}`
// yields: December 23rd, 2010
Note - all of this will likely change, hopefully for the better, when temporal becomes a reality in JS: https://github.com/tc39/proposal-temporal. Look forward to somebody's 2030 update of this post!

Categories

Resources