Convert string to date format using javascript - javascript

I have a string value and i need to convert that string value to the following date format using javascript.
var strDate = "2016-11-20";
expected output is: 20-Nov-2016
How Can I change this?

javascript have rich set of Date function e.g.:
new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, date[, hours[, minutes[, seconds[, milliseconds]]]]]);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
also already answered here :
Converting string to date in js
I have a UTC string and I want to convert it to UTC Date Object in JavaScript
We can mark this question duplicate

A little workaround could be the following, but if you have to manipulate dates a lot, I strongly recommend you to use the Moment.js library:
https://momentjs.com/
var strDate = "2016-11-20";
var utcDate = new Date(strDate).toUTCString();
var convertedDate= utcDate.substring(utcDate.lastIndexOf(", ") + 1, utcDate.lastIndexOf(" 00:"));
console.log(convertedDate.trim().replace(/\s/g, '-'));
Pay attention that the implementation of this method may change depending on the platform. Here from the official doc:
The value returned by toUTCString() is a human readable string in the
UTC time zone. The format of the return value may vary according to
the platform. The most common return value is a RFC-1123 formatted
date stamp, which is a slightly updated version of RFC-822 date
stamps.

Related

How to convert into Date time

When the date is passed from my c# to JavaScript it returns the date time as {4/3/2020 12:00:00 AM}
but in JavaScript it is shown as 1585852200000.
What is the format that is being used? And how can i convert it back?
You need to convert the Unix timestamp to DateTime format,
var localDate = new Date(1585852200000).toLocaleDateString("en-US")
console.log(localDate); // only local date
var localTime = new Date(1585852200000).toLocaleTimeString("en-US")
console.log(localTime) // only local time
// local datetime
console.log(new Date(1585852200000).toLocaleString());
1585852200000 is epoch date.
you can convert it as
var date = new Date(1585852200000)
console.log(new Date(1585852200000));
As an alternative from Shivaji's answer:
When you are passing the date through to JS you could cast it as a string with DateTime.ToString("dd/MM/yyyy") seen here on MSDN.
This will keep its integrity visually, if it is just for display purposes, otherwise you will need to re-cast appropriately in JS (in which case use Shivaji's answer).
JavaScript Date's object will return the DATE object and it's POSITION that is being assigned in your computer. So, when you are working with a date or datetime types, you can use some of the methods that are provided by the Date object, such as getDate() and getDay(). But, a better solution would be to format the Date object itself. For example: use the toString() or toUTCString() methods.
var d = new Date();
document.getElementById("demo").innerHTML = d.toString();
Reference:
https://www.w3schools.com/js/js_date_formats.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Given string format to date

I have given a very unusual date format in string. I need to convert it to a JS date object and add up a few days. The last step is clear, but I don't know how to convert the string into the JS date object. Take a look at the string date: October 02, 2016
You should use moment.js
Syntax:
moment(dateString, format, locale)
var dateStr = "Oktober 02, 2016"
var d = moment(dateStr, "MMM DD, YYYY", 'de');
console.log(d.format("DD-MM-YYYY"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment-with-locales.min.js"></script>
Use Date.parse() to parse the date and get the Date object.
var dateObj = new Date('October 02, 2016')
Now, you can perform all the Date operations on dateObj
Given that everything is static here, I thing the best case for you might be to keep a map of your month's name against there number i.e say Oktober : 8. This way you will easily get around of any locale issue in any library.
Once above map is done, you can use .substring to separate your string for blank space and commas to get date and year easily.
Once you have all this you can use new Date constructor with months date and year field.
Hope this all is easily understood, so I am skipping any code here.
Using new Date() can be converted from string to date.
And using setDate() you can add days in the date and can convert the date back to string,
Please check below snippet for more understanding.
var someDate = new Date('October 02, 2016');
console.log(someDate);
console.log(new Date(someDate.setDate(someDate.getDate() + 5)).toString());

How to do a date format in Javascript?

I need to understand how to do date formattting in javascript.
i have date as,
var date="12/02/1994";// dd/mm/yyy
var date1=new Date(date);
date1.getDate();// this gives me Month which is 02
date1.getMonth();// this gives me date which is 12.
How do i get the exact date i have in var date in get date and getmonth function? Please help
The answer is pretty simple: JavaScript uses mm/dd/yyyy data format.
It doesn't support dd/mm/yyyy format, so, if you need to parse this format, then you will have to do this manually like this:
function parseDdmmyyyy(str)
{
var spl = str.split('/');
return new Date(spl[2], spl[1] - 1, spl[0]);
}
or you will have to use external libraries like Moment.js.
Javascript date() expects date in mm/dd/yy and not in dd/mm/yy. And months start from 0 and not 1.
var from = "12/02/1994".split("/");
var date1 = new Date(from[2], from[1] - 1, from[0]);
date1.getDate();
date1.getMonth();
Use new Date('02/12/1994'), new Date('1994-02-12') or new Date(1994, 02-1, 12), because in js months start from 0 and american date format is used where month goes first
you can use the simple JS file DateFormat.js which has some very good example through the URL mattkruse (Date Funtion)
from this JS file you can validate the incoming date is a true format even you can add format date within a several ways.
Presumably you want to know how to format strings so they are consistently parsed by browsers. The short answer, is there is no guarantee that any particular string will be correctly parsed by all browsers in use (or perhaps even most).
So the bottom line is: don't parse strings with the Date constructor, ever. It's largely implementation dependent and even the one format specified in ES5 and ECMAScript 2015 is poorly and inconsistently supported.
How browsers treat a string like "12/02/1994" is entirely implementation dependent, however most will treat it as the peculiar US month/day/year format, i.e. 2 December and getMonth will return 11, since months are zero indexed.
So you should always manually parse strings (a library can help, but a simple parsing function is only 2 lines, 3 if validation is required), e.g.
// Parse a date string as d/m/y
// If s is not a valid date, return a Date object with its
// time value set to NaN.
function parseDMY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[1], b[0]);
return d && b[1] == d.getMonth()? d : new Date(NaN);
}
document.write(parseDMY('12/02/1994'));

Turn string into date - JavaScript

Hey guys I am retrieving a value from an input box and am using that value to turn into a Date for JavaScript the format is Y-m-d h:i:s. It works perfect in Chrome but any other browser says invalid Date
var old = $(".checked-in-time").val();
old = new Date(old);
UPDATE:
Here is what I am doing:
var current = new Date();
var old = $(".checked-in-time").val();
old = Date.parse(old , 'Y-m-d H:i:s');
var newEnd = current - old
minutes = parseInt((newEnd/(1000*60))%60);
var subtractedWaitTime = minutes;
Pretty much getting the time difference based on minutes.
Date.parse accepts a limited number of formats:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
Your format is not one of the ones supported. You can parse it yourself and just pass the arguments directly. One of the forms Date accepts is this, which would be easy enough to pull out from your format:
new Date(year, month[, date[, hour[, minutes[, seconds[, milliseconds]]]]]);
But I would recommend removing the pain of having to worry about cross browser compatibility and parsing things yourself, and use moment instead, where you can parse the date like this
moment(dateStr,'YYYY-M-D H:m:s')
and then if you needed to have it as a Javascript Date object you could just run
moment().toDate();
in the more likely case you just need to display it formatted somewhere, or compare it to other dates, moment offers many functions for formatting, manipulating and comparing dates
http://momentjs.com/docs/#/displaying/as-javascript-date/
Try one of the following formats
MM-dd-yyyy
yyyy/MM/dd
MM/dd/yyyy
MMMM dd, yyyy
MMM dd, yyyy
Could be that some browsers don't support yyyy-mm-dd
You can parse date like this,
var old = $(".checked-in-time").val();
old = Date.parseDate(old , 'yyyy-mm-dd h:i:s');
if the above not working, you can also try Y-m-d H:i:s this format. For me Y/m/d H:i worked fine.
You could try use such format Y-m-dTH:i:s, e.g. 2011-01-01T12:00:00
Or you can use moment library (Javascript Date library)

How to create object of Date("23.03.2010")

I have astring directly coming form the database and I am creating object of Date as
Date dt=Date("23.03.2010") and it is comin NaN
whereas when I use Date dt= Date("03/23/2010") it works fine.
Any Idea how I can get this working?.
You can parse the string from the database and then create the date object. You will have to subtract 1 from the parsed month value to get a correct date.
var dateString = "23.03.2010";
var dateParts = dateString.split(".");
var dt = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
You must pass string (parsed) dates in MDY format. This is to prevent ambiguity (does 5/6/2010 mean 6th May or 5th June?)
If you prefer, you can use new Date(year, month, day) format, and pass the arguments separately.
The safest way if is you can return the date as milliseconds since 1970-01-01, then you can easily create a Date object from it. Example:
var n = 1269302400000;
var dt = new Date(n);
Note that you'll want to invoke Date with the new operator - from the Mozilla Developer Center:
Invoking Date in a non-constructor
context (i.e., without the new
operator) will return a string
representing the current time.
The same page details the syntax of the Date constructor.
If you are constructing a Date from a string the format accepted is governed by the rules of the Date.parse method. See Microsoft's Date.parse documentation for a summary of these rules.
Give this a try...
var dateParts = '23.03.2010'.split('.');
// -1 from month because javascript months are 0-based
var dateObj = new Date(dateParts[2], dateParts[1]-1, dateParts[0]);
try
d="23.03.2010".split(".");
Date dt=Date([d[1],d[0],d[2]].join("/"))
i think it isn't the most beautiful way.

Categories